Vue Tip: watch() vs. watchEffect()

Michael Hoffmann
Jun 22, 2022
| 1 min read
| 600 views
Michael Hoffmann
Jun 22, 2022
1 min read
| 600 views
Script
%20vs.%20watchEffect()/vue_tip_template.jpg)
We can use the watch()
hook to trigger a callback whenever a piece of reactive state changes. It also enables us to access the previous value of the watched variables:
1
<script>
2
// The callback is called whenever 'refA' changes
3
watch(refA, () => {
4
console.log(refA.value)
5
console.log(refB.value)
6
})
7
</script>
The watchEffect()
hook works like the computed()
hook or the computed option, but instead of returning a value, you use it to trigger side-effects:
1
<script>
2
// The callback is called immediately, and whenever 'refA' or 'refB' changes
3
watchEffect(() => {
4
console.log(refA.value)
5
console.log(refB.value)
6
})
7
</script>
watchEffect()
might seem superior to watch()
, but if you only want to trigger the callback function when one or multiple specific variables change, you must use watch()
instead of watchEffect()
.
If you liked this Vue tip, follow me on Twitter to get notified about new tips, blog posts, and more. Alternatively (or additionally), you can subscribe to my weekly Vue newsletter:
New Vue & Nuxt tips delivered to your inbox:
Vue Tip: Use Fallthrough AttributesJun 15, 2022
Vue Tip: Memoize a Sub-Tree of the Template Using v-memoJun 29, 2022
Show comments