Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 87 ยท Reactivity Fundamentals

Watchers

Learn Vue watchers - watch sources, deep, immediate and once options, flush timing, watchEffect, stopping watchers and cleaning up side effects such as stale requests.

A computed property answers the question "what is this value?" A watcher answers a different one: "when this changes, what should I do?" Typical answers are side effects: call an API, save a draft, start or stop a timer, write to the console, or update something outside Vue's control, like a chart library or the page title.

Vue gives you two watcher functions. watch observes specific sources and hands you the new and old values. watchEffect runs a function immediately and re-runs it whenever any reactive value it used changes. This lesson covers both, their options, when they run, and how to stop and clean up after them.

The basics of watch

watch(source, callback, options) calls callback(newValue, oldValue, onCleanup) after the source changes. The source can be:

  • a ref (or computed),
  • a reactive object (watched deeply),
  • a getter function that returns a value,
  • an array of any of the above.

A property of a reactive object is not a valid source on its own. watch(state.count, ...) passes a plain number, which Vue cannot observe (it prints a warning). Wrap it in a getter: watch(() => state.count, ...).

Watch sources and options

Right after mounting you see one line: immediate: 0, old = undefined. Then try the buttons in this order and watch which lines appear:

  • count++ fires the plain watcher, the immediate watcher, and the once watcher, which then removes itself. A second count++ produces only two lines.
  • Rename fires the getter watcher on user.value.name and the deep watcher, but not the shallow one.
  • Move city fires only the deep watcher. The getter watches name, and the shallow watcher cares only about the ref's value being replaced.
  • Replace user fires all three user watchers, because the object itself is new.

The rule behind this: a watcher re-runs when the value it returns is different (compared with Object.is), or, with deep, when anything inside that value changes.

The options

  • immediate: true runs the callback once right away, with undefined as the old value. Good for "load for the starting value, then reload on change".
  • deep: true traverses the whole value, so nested mutations count. Because the object is the same one after a mutation, newValue === oldValue inside a deep callback. Deep watching a large structure costs time proportional to its size. Since Vue 3.5, deep can also be a number, the maximum depth to traverse.
  • once: true (Vue 3.4+) runs the callback at most once and then stops the watcher.
  • flush controls timing (next section).

A watcher on a reactive object (not a ref) is deep automatically. A getter that returns an object is not: it fires only when the getter returns a different object, unless you add deep: true.

When callbacks run: flush timing

Watcher callbacks do not run in the middle of your assignment. Vue queues them and runs them together. By default (flush: "pre") they run before the component's DOM is updated, so inside the callback the DOM still shows the old state. Two other modes exist:

  • flush: "post" runs after the DOM update, which is what you need when the callback reads sizes or positions of rendered elements.
  • flush: "sync" runs immediately and synchronously on every change. It disables batching, so use it rarely.
flowchart LR
    A["State changes"] --> B["pre watchers run"]
    B --> C["Component re-renders, DOM updates"]
    C --> D["post watchers run"]

Default watchers run before the render; flush: "post" watchers run after the DOM has been patched.

If several changes happen in the same tick, a watcher runs once with the latest value, not once per change. DOM Update Timing and nextTick goes deeper into this batching.

watchEffect: track whatever you read

With watch you list the sources. With watchEffect you simply write the code, and Vue records which reactive values it reads while running. The effect runs immediately and again whenever any of those change. There is no old value and no immediate option, because it always runs first.

Two details matter:

  • Only values read synchronously are tracked. Anything after an await is invisible to it.
  • Dependencies are re-collected on every run. If a branch stops reading a value, changes to that value no longer trigger the effect.
watchEffect and stopping a watcher

The first line says total = 3. Press b++ and the effect runs again with total = 4. Now press Toggle include b: the effect runs once more (total = 1), and on that run it no longer reads b. From then on b++ does nothing, while a++ still re-runs it. Finally Stop effect calls the function that watchEffect returned; after that no button produces a new line.

Choose between the two like this: if you need the old value, or you want the callback to fire only for particular sources, use watch. If the effect should simply stay in sync with everything it reads, watchEffect is shorter.

flowchart TD
    Q{"What do you need?"}
    Q -->|"a value derived from state"| C["computed"]
    Q -->|"a side effect when specific sources change"| W["watch"]
    Q -->|"a side effect that follows whatever it reads"| E["watchEffect"]

Computed returns a value; watch and watchEffect perform side effects.

Stopping watchers

A watcher created synchronously during setup() is tied to the component and stops automatically when the component unmounts. You do not need to do anything.

A watcher created later, for example inside a setTimeout or after an await, is not attached to the component and keeps running forever unless you stop it yourself. Both watch and watchEffect return a handle:

JavaScript
const stop = watch(source, callback);

stop(); // stop for good

Since Vue 3.5 the handle also has pause() and resume(). A paused watcher ignores changes; after resume() it runs once if its sources changed meanwhile. Use pause for temporary suspension and stop() when you are done with the watcher.

Cleaning up side effects

Side effects often leave something behind: a pending request, a timer, an event listener. If the source changes again before the effect finished, the old work is now stale. The third argument to a watch callback, onCleanup, registers a function that Vue calls before the next run of the callback and when the watcher stops.

The classic case is a search box. Typing v, vu, vue should not let the answer for v arrive after the answer for vue and overwrite it. The demo below uses a timer as a stand-in for a network request, so it works inside the sandbox.

Cancel stale work with onCleanup

After about a fifth of a second the list reads: started v, cancelled v, started vu, cancelled vu, started vue, finished vue. The first two requests never reached their "finished" line, so only the newest result ever updates the status.

Vue 3.5 also offers onWatcherCleanup(fn), imported from "vue". It does the same job without the extra parameter, so a helper function can register cleanups too. It must be called synchronously inside the callback, before any await.

Common mistakes

  • Using a watcher to derive state. If you write watch(first, () => { full.value = first.value + last.value }), you wanted a computed. Watchers for derived values run later than computeds and add an extra render.
  • Changing the watched source inside its own watcher without a stop condition. That schedules the watcher again and can loop forever (Vue stops it with a "recursive updates" warning, but do not rely on that).
  • Expecting deep: true to give you the old object. For a mutated object, old and new values are the same reference. Keep a copy if you need the previous state.
  • Reading reactive values after an await in watchEffect, then wondering why changes are ignored. Read them first, into local variables.
  • Forgetting cleanup for requests and timers, which produces flickering results and memory leaks.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which call correctly watches the count property of a reactive object called state?

    state.count is just a number when passed directly, so Vue cannot track it. A getter function lets Vue see the reactive read and re-run when it changes.
  2. 2. A watcher uses the default flush option. When does its callback run in relation to the DOM update?

    The default is flush: 'pre', so callbacks run before the component re-renders. Use flush: 'post' to run after the DOM is patched.
  3. 3. What is onCleanup (the third argument of a watch callback) mainly for?

    The registered function runs before the callback runs again and when the watcher is stopped, so you can clear timers, abort requests and remove listeners.
  4. 4. You create a watcher inside a setTimeout callback. What should you do?

    Only watchers created synchronously during setup are bound to the component. A watcher created later keeps running until you call the stop handle.
  5. 5. Why does a watchEffect that reads a ref only after an await miss changes to that ref?

    Dependency tracking happens while the function runs synchronously. After an await, Vue no longer knows which effect is running, so later reads are not recorded.

Summary

  • watch(source, (newValue, oldValue, onCleanup) => ...) runs side effects when specific sources change; sources are refs, reactive objects, getters or arrays of those.
  • immediate runs once at creation, deep traverses nested changes, once stops after the first run.
  • Callbacks are batched and run before the DOM update by default; flush: "post" runs after it.
  • watchEffect runs immediately and tracks everything it reads synchronously, re-collecting dependencies on every run.
  • Watchers created in setup() stop with the component; others must be stopped through the returned handle (stop, plus pause and resume in Vue 3.5).
  • Register cleanups with onCleanup or onWatcherCleanup to cancel stale requests and timers.
  • Use computed for derived values and watchers only for side effects.

Next, look under the hood in How Reactivity Works.