What is watch()?
watch() is a function from the Composition API (Vue 3) that lets you observe changes to reactive data and run side effects when that data changes.
In simpler terms:
watch()"watches" a reactive value, and when it changes, it runs a handler function.
This is the equivalent of watch from the Options API, but more flexible.
Simple usage of watch()
import { ref, watch } from 'vue'
const count = ref(0)
watch(count, (newVal, oldVal) => {
console.log('count changed:', oldVal, '→', newVal)
})When count.value++ runs, the handler fires.
What can you watch?
1. a ref
watch(count, ...)2. a reactive object (by reference only!)
watch(form, () => {
console.log('The form changed (any field)')
})3. a specific field of a reactive object
watch(() => form.email, (newVal) => {
console.log('email changed:', newVal)
})4. an array of dependencies
watch([foo, () => bar.value], ([newFoo, newBar]) => {
console.log(newFoo, newBar)
})When do you use watch()?
1. For side effects
Things that should not be inside computed:
- server requests
- saving drafts
- logging
- updating localStorage
- interacting with third-party libraries
Example:
watch(query, () => {
fetchData(query.value)
})2. For deep tracking of objects
watch(form, (newVal) => {
console.log('some field in the form changed')
}, { deep: true })3. For reacting to route, props, or URL parameter changes
watch(() => route.params.id, (id) => {
loadUser(id)
})4. For debounce or throttle
watch(search, debounce((val) => {
fetchSearch(val)
}, 500))watch() options
1) deep - deep observation
watch(obj, handler, { deep: true })2) immediate - call right away on initialization
watch(count, handler, { immediate: true })(very useful for loading data)
3) flush - when to call the handler
pre(default, before the DOM updates)post(after the DOM updates)sync(immediately)
Example:
watch(value, handler, { flush: 'post' })Used for working with the DOM after data changes.
watch() vs computed() - an important topic for interviews
| watch | computed |
|---|---|
| performs side effects | returns a computed value |
| asynchronous | synchronous |
| can be deep | only works with its dependencies |
| not cached | cached |
| for API calls, logic, effects | for derived data |
If you "need to get a value" → computed. If you "need to do something on change" → watch.
Example: using watchEffect
Comparison:
watch(() => count.value, (n) => console.log(n))vs
watchEffect(() => {
console.log(count.value)
})watchEffect() automatically collects its dependencies.
Summary (ideal for an interview)
watch()is a function for tracking changes to reactive data and running side effects. It's used for API requests, logic, side effects, synchronization, and saving data. It supports deep, immediate, an array of dependencies, and flush modes. It differs from computed in that it performs actions instead of returning a value.
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.