All quizzesMedium
watch & Composables
Preview — 3 of 10 questions
What is the primary difference between watch and watchEffect in Vue 3?
javascript
import { ref, watch, watchEffect } from 'vue'
const count = ref(0)
const name = ref('Alice')
// watchEffect — runs immediately, auto-tracks dependencies
watchEffect(() => {
console.log(`count: ${count.value}, name: ${name.value}`)
// Automatically watches both count and name
})
// watch — explicit source, lazy by default (won't run on init)
watch(count, (newVal, oldVal) => {
console.log(`count changed from ${oldVal} to ${newVal}`)
})
// watch with multiple sources
watch([count, name], ([newCount, newName], [oldCount, oldName]) => {
console.log(`count: ${oldCount} → ${newCount}, name: ${oldName} → ${newName}`)
})Awatch is asynchronous; watchEffect is synchronous
BwatchEffect only works with reactive; watch only works with ref
CwatchEffect tracks dependencies automatically; watch requires explicitly specifying sources
Dwatch runs immediately on mount; watchEffect does not
What does the { immediate: true } option do in watch?
javascript
import { ref, watch } from 'vue'
const userId = ref(1)
watch(userId, async (newId) => {
const user = await fetchUser(newId)
console.log(user)
}, { immediate: true }) // Fetches data for userId=1 immediately on setupAMakes the watcher run synchronously instead of asynchronously
BMakes watch behave identically to watchEffect
CPrevents the watcher from being stopped when the component unmounts
DRuns the callback immediately when the watcher is created, before any change
What is the correct usage of provide and inject in Vue 3 Composition API?
javascript
// Parent component — provides data
import { provide, ref } from 'vue'
const theme = ref('dark')
const updateTheme = (newTheme) => { theme.value = newTheme }
provide('theme', theme)
provide('updateTheme', updateTheme)
// Descendant component (any depth) — injects data
import { inject } from 'vue'
const theme = inject('theme') // Reactive ref
const updateTheme = inject('updateTheme')
// With default value (in case no parent provides it)
const theme = inject('theme', ref('light'))AA parent component uses provide to share data; descendant components use inject to receive it
BBoth provide and inject must be used in the same component
Cprovide is used in child components; inject is used in parent components
Dprovide/inject only works between direct parent-child components, not deeper descendants
Sign up free to play
Answer all 10 questions (7 more), see explanations for every answer, and track your score.