← Back to Vue.js Course | Chapter 9: Composables & Composition API | Lesson 6 of 7

watch/watchEffect

watch reacts to specific sources, while watchEffect runs immediately and re-runs whenever anything it reads changes.

In this page:

  1. watch/watchEffect
Syntax
markup
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

markup
<!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
  1. Expecting watch to run immediately
  2. Creating watchers asynchronously and leaking them
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.