watch/watchEffect
watch reacts to specific sources, while watchEffect runs immediately and re-runs whenever anything it reads changes.
In this page:
Syntax
watch(source, (newValue, oldValue) => {
// react to change
});
watchEffect(() => {
// runs immediately and re-runs when used values change
});
watch/watchEffect
watch(source, callback) is lazy by default and gives new and old values. watchEffect(fn) runs at once, tracks every reactive value read inside and re-runs on change, with no old value.
Both return a stop function and support flush timing and cleanup callbacks.
Note:
Use watch when you need old values or explicit sources, and watchEffect for simple side effects.
Example: watch/watchEffect
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
</head>
<body>
<div id="app"><button @click="n++">n = {{ n }}</button><p>{{ log.join(" ; ") }}</p></div>
<script>
Vue.createApp({
setup() {
const n = Vue.ref(1);
const log = Vue.ref([]);
Vue.watch(n, (newV, oldV) => log.value.push(`watch ${oldV}->${newV}`));
Vue.watchEffect(() => log.value.push("effect sees " + n.value));
return { n, log };
},
}).mount("#app");
document.querySelector("button").click();
Vue.nextTick(() => setTimeout(() => console.log(document.querySelector("p").textContent), 20));
</script>
</body>
</html>
<!-- Output:
Rendered: n = 2effect sees 1 ; watch 1->2 ; effect sees 2
console: effect sees 1 ; watch 1->2 ; effect sees 2
-->
Live Example
Related Topics
Common Mistakes
- Expecting watch to run immediately
- Creating watchers asynchronously and leaking them
- Reading reactive values conditionally in watchEffect
Chapter Summary
- watch is explicit and lazy
- watchEffect tracks automatically
- Both return stop functions
- watch gives old and new values
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: