Vue in Vue is best learned by connecting the rule to a small admin screen. Start with the smallest component or composable, observe the output, and then add one realistic constraint so the concept becomes practical.
The key habit for this lesson is to watch ref, prop, slot, or emitted event as it changes. That makes the topic easier to debug, easier to explain in interviews, and easier to use in real code without memorizing isolated syntax.
Watchers let you run side effects in response to reactive data changes - things that computed properties can't do: async operations, DOM manipulation, calling external APIs, or logging.
| Feature | watch() | watchEffect() |
|---|---|---|
| Source declaration | Explicit - you specify what to watch | Automatic - tracks all accessed refs |
| Runs immediately | No (unless immediate: true) | Yes - runs on creation |
| Old value access | Yes - (newVal, oldVal) | No |
| Best for | Specific data changes, need old value | Multiple deps, immediate execution |
<template>
<div>
<input v-model="query" placeholder="Search..." />
<input v-model.number="userId" type="number" placeholder="User ID" />
<p>{{ status }}</p>
</div>
</template>
<script setup>
import { ref, reactive, watch, watchEffect, onUnmounted } from 'vue'
const query = ref('')
const userId = ref(1)
const status = ref('Ready')
const user = reactive({ name: '', email: '' })
// 1. Watch a single ref
watch(query, (newVal, oldVal) => {
console.log(`Query changed: "${oldVal}" -> "${newVal}"`)
status.value = `Searching for: ${newVal}`
})
// 2. Watch with options
watch(userId, async (newId) => {
status.value = 'Loading...'
const res = await fetch(`/api/users/${newId}`)
const data = await res.json()
user.name = data.name
user.email = data.email
status.value = 'Loaded'
}, {
immediate: true, // run immediately on mount
flush: 'post', // run after DOM updates
})
// 3. Watch multiple sources
watch([query, userId], ([newQuery, newId], [oldQuery, oldId]) => {
console.log('Either changed:', newQuery, newId)
})
// 4. Watch reactive object - need getter or deep: true
const form = reactive({ name: '', email: '' })
// Watch specific property with getter
watch(() => form.name, (newName) => {
console.log('Name changed:', newName)
})
// Watch entire reactive object (deep)
watch(form, (newForm) => {
console.log('Form changed:', newForm)
}, { deep: true })
// 5. watchEffect - auto-tracks dependencies
const stop = watchEffect(() => {
// Automatically tracks query.value and userId.value
document.title = `${query.value} | User ${userId.value}`
console.log('Effect ran')
})
// 6. watchEffect with cleanup
watchEffect((onCleanup) => {
const timer = setTimeout(() => {
console.log('Debounced:', query.value)
}, 500)
onCleanup(() => clearTimeout(timer)) // cleanup before next run
})
// 7. Stop a watcher manually
onUnmounted(() => stop()) // stop watchEffect when component unmounts
</script>
<template>
<div>
<input v-model="searchQuery" placeholder="Search users..." />
<p v-if="loading">Searching...</p>
<ul v-else>
<li v-for="user in results" :key="user.id">{{ user.name }}</li>
<li v-if="results.length === 0 && searchQuery">No results</li>
</ul>
</div>
</template>
<script setup>
import { ref, watch } from 'vue'
const searchQuery = ref('')
const results = ref([])
const loading = ref(false)
// Debounced search with watch + cleanup
watch(searchQuery, (newQuery, _, onCleanup) => {
if (!newQuery.trim()) {
results.value = []
return
}
loading.value = true
// AbortController to cancel previous request
const controller = new AbortController()
const timer = setTimeout(async () => {
try {
const res = await fetch(`/api/users?q=${newQuery}`, {
signal: controller.signal
})
results.value = await res.json()
} catch (err) {
if (err.name !== 'AbortError') console.error(err)
} finally {
loading.value = false
}
}, 400) // 400ms debounce
// Cleanup: cancel request and clear timer if query changes
onCleanup(() => {
clearTimeout(timer)
controller.abort()
loading.value = false
})
})
</script>
Understanding Watchers is not just about syntax. In production applications, this topic directly affects maintainability, debugging speed, and team collaboration. Focus on readability, small reusable patterns, and predictable state flow when implementing Watchers.
A practical approach is to first implement the simplest working version, then refactor into reusable pieces (components/composables/stores) only when duplication appears. This helps keep your Vue codebase clean while avoiding over-engineering.
Use Vue when the program needs a clear answer to a specific problem, not because the keyword looks familiar. In a real Vue task, first name the input, then name the transformation, then name the output. This small discipline shows whether the topic is being used correctly or only copied from an example.
A reliable practice flow is: create the smallest working component or composable, add one normal case, add one edge case such as cleanup after async requests, and then confirm the result with Vue Devtools and template warnings. If the result surprises you, reduce the code until the behavior is visible again.
The most common trap here is using a watcher for derived state that should be computed. Avoid it by writing one sentence before the code that explains why Vue is the right choice. After the code runs, verify the lesson by doing this: change the source ref twice and inspect the final side effect.
Using a watcher for derived state that should be computed.
Write the expected behavior first, then make the example prove it.
Practicing only the perfect input.
Also test cleanup after async requests before considering the lesson complete.
Looking only at the final output.
Trace ref, prop, slot, or emitted event through each important step.
Use it when the problem matches the behavior shown in the example and when the result can be verified through Vue Devtools and template warnings.
Start with a tiny case, then test cleanup after async requests. The main warning sign is using a watcher for derived state that should be computed.
Trace ref, prop, slot, or emitted event, predict the result, run the example, and compare your prediction with the actual output.
Explore 500+ free tutorials across 20+ languages and frameworks.