Would you like to buy me a ☕️ instead?
When I first studied the new Composition API, I was confused that there are two watch hooks: watch()
and watchEffect()
. From the documentation alone, it was not immediately apparent to me what’s the difference.
The Difference Between watch
and watchEffect
Assuming you already know how watch()
works with the Options API, it is easy to understand how the watch()
hook works.
The
watch()
hook works like thewatch
option.
The watchEffect()
hook’s main difference is that you don’t watch one specific reactive value but every reactive value inside its callback function.
The
watchEffect()
hook works like thecomputed()
hook or thecomputed
option, but instead of returning a value, you use it to trigger side-effects.
// The callback is called whenever `refA` changes.
watch(refA, () => {
console.log(refA.value);
console.log(refB.value);
});
// The callback is called immediately, and
// whenever `refA` or `refB` changes ...
watchEffect(() => {
console.log(refA.value);
console.log(refB.value);
});
// ... this is the same behavior as for `computed()`.
const aPlusB = computed(() => {
console.log(refA.value);
console.log(refB.value);
return refA.value + refB.value;
});
Do you want to learn more about advanced Vue.js techniques?
Register for the Newsletter of my upcoming book: Advanced Vue.js Application Architecture.
When Should I Use watch
?
At first glance, watchEffect()
seems superior to watch()
. Because you simply define a callback function, and it is automatically triggered if one of the reactive variables you use inside of it changes. But this behavior can be problematic. If you only want to trigger the callback function when one or multiple specific variables change, you must use watch()
instead of watchEffect()
.
Furthermore, using watch()
also enables us to access the previous value of the watched variables.
Wrapping It Up
I think the easiest way to remember the difference between watch
and watchEffect()
is to think of watchEffect()
like a variant of computed()
that doesn’t return a value but triggers side-effects.