Watchers with watch and watchEffect

Intermediate · 9 min

Running side effects when reactive state changes with watch and watchEffect, plus sources, deep and immediate, flush timing, and cleanup.

Before thisref and reactiveComputed properties

Program With Erik · 9 min

Watchers with watch and watchEffect

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Program With ErikReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • Computeds derive values; watchers do things. Reach for a watcher when a state change should cause a side effect such as a network request, a `localStorage` write, or a call into a non-Vue library.
  • `watch(source, callback)` is explicit and lazy: you name what to watch, the callback receives the new and old values, and it does not run until the source first changes unless you pass `immediate: true`.
  • `watchEffect(fn)` runs immediately and re-runs whenever any reactive value it read changes. It saves listing dependencies, but in an async function only reads before the first `await` are tracked.
  • A watch source must be a ref, a reactive object, a getter function, or an array of those. To watch one property of a reactive object, pass a getter: `watch(() => state.id, ...)`.
  • Watchers run before the component's DOM update by default (`flush: 'pre'`). Use `flush: 'post'` to read the updated DOM, and register cleanup with `onWatcherCleanup()` (Vue 3.5+) or the callback's `onCleanup` argument to cancel stale async work.
  • Watchers created synchronously in `setup` stop automatically when the component unmounts. The returned handle can stop them early and, since 3.5, pause and resume them.

Values versus effects

A computed answers “what is this value, given that state?” Some changes need a different answer: “when this changes, go do something.” Save the draft to localStorage. Fetch the user whose id is in the URL. Tell a chart library to redraw. None of these produce a value for the template. They reach outside the component, and the timing matters.

That is what watchers are for. Vue gives you two: watch, where you name exactly what to observe, and watchEffect, which observes whatever it happens to read.

watch: explicit and lazy

<script setup>
import { ref, watch } from 'vue'

const draft = ref(localStorage.getItem('draft') ?? '')

watch(draft, (newValue, oldValue) => {
  localStorage.setItem('draft', newValue)
})
</script>

<template>
  <textarea v-model="draft" />
</template>

The first argument is the source and the second is the callback. The callback receives the new value and the previous value, which is handy for “only act if it went from A to B.” By default watch is lazy: the callback does not run when the watcher is created, only after the source first changes.

The source has to be something Vue can observe:

watch(count, cb)                        // a ref (or computed)
watch(state, cb)                        // a reactive object: implicitly deep
watch(() => state.userId, cb)           // a getter: watch one property
watch(() => a.value + b.value, cb)      // a getter: watch a derived value
watch([firstName, () => state.age], cb) // an array of sources

The most common mistake is watch(state.userId, cb). That expression evaluates to a plain number before watch ever sees it, so there is nothing to observe. Wrapping it in a getter lets Vue run the function, see which reactive values it reads, and re-run it when they change.

Options: immediate, deep, once

watch(userId, fetchUser, { immediate: true })   // also run once right now
watch(settings, save, { deep: true })           // fire on nested mutations
watch(() => form.address, save, { deep: 1 })    // Vue 3.5+: only one level deep
watch(token, refreshSession, { once: true })    // Vue 3.4+: fire a single time

immediate: true is common for “load data now, and again whenever the id changes.” Watching a getter that returns an object only fires when the getter returns a different object. Add deep: true to also fire on nested property changes. Passing a reactive() object directly is already deep. With deep watching, newValue and oldValue are the same object when you mutated it in place, since there is no copy of the old state. Deep watching traverses the whole structure on every change, so on large objects prefer a getter that targets exactly what you care about.

watchEffect: track whatever you read

import { ref, watchEffect } from 'vue'

const userId = ref(1)
const user = ref(null)

watchEffect(async () => {
  const response = await fetch(`/api/users/${userId.value}`)
  user.value = await response.json()
})

watchEffect runs the function immediately, records every reactive value read during that run, and re-runs whenever one of them changes. There is no source list to keep in sync, which is pleasant when an effect depends on several values.

The trade-off is precision. You do not get old values, and dependency tracking only happens during the synchronous part of the run. In the example, userId.value is read before the first await, so it is tracked. Anything read after an await is not. A safe habit: read all the reactive values you depend on at the top of the function.

A rule of thumb that matches the video: use watch when you want laziness, old values, or a precise trigger; use watchEffect when the effect’s dependencies are exactly the values it reads, and running once at the start is what you want anyway.

Cleanup and stale async work

Async effects race. If userId changes from 1 to 2 while the request for user 1 is still in flight, and the first response arrives last, it overwrites the right answer with the wrong one. Watchers let you register cleanup that runs right before the next run, and when the watcher stops:

import { watch, onWatcherCleanup } from 'vue'

watch(userId, async (id) => {
  const controller = new AbortController()
  onWatcherCleanup(() => controller.abort()) // Vue 3.5+

  const response = await fetch(`/api/users/${id}`, { signal: controller.signal })
  user.value = await response.json()
})

onWatcherCleanup must be called synchronously, before any await, because Vue needs to know which watcher is running. Before 3.5, the same thing is done with the third callback argument: watch(userId, async (id, oldId, onCleanup) => { onCleanup(() => controller.abort()) ... }). watchEffect passes onCleanup as its function’s first argument. This is the same race React handles with an effect’s cleanup function, covered in cleanup and race conditions in effects.

Flush timing

When a watched value changes, Vue batches the resulting work. By default (flush: 'pre'), watcher callbacks run before the component re-renders, so the DOM still shows the old state. If the callback needs the updated DOM, such as measuring an element’s height after a list grows, use flush: 'post' or the shorthand watchPostEffect. flush: 'sync' runs the callback synchronously on every single change with no batching. It exists for rare cases and is easy to make slow.

Stopping watchers

Watchers created synchronously during <script setup> are tied to the component and stop on unmount automatically. A watcher created later, such as inside a setTimeout or a promise’s .then() callback, is not, and must be stopped by hand to avoid a leak:

const handle = watch(source, cb)

handle.stop()   // or call handle() directly
handle.pause()  // Vue 3.5+: stop reacting for now
handle.resume() // Vue 3.5+: pick up again

What the video covers

Erik’s video is about the decision at the heart of this lesson: watch versus watchEffect. It walks through three concrete differences (watch runs lazily, triggers on a more specific source, and gives you previous and current values), then flags a few traps. It dates from early 2022, so it predates once, numeric deep, onWatcherCleanup, and pause/resume. Those are carried above. Alexander Lichter’s 2025 video in the “go deeper” links is the best treatment of flush timing, with a demo of when post and sync matter.

Where this fits

Watchers, computeds, and component rendering are all built on one mechanism. How Vue reactivity works opens it up. Watchers also connect to the component’s lifetime, covered in lifecycle hooks.

Check yourself

  1. 01Why does `watch(state.count, cb)` fail when `state` is a `reactive()` object, and what should you write instead?

    `state.count` is evaluated before `watch` is called, so `watch` receives a plain number, which is not something Vue can observe. Pass a getter, `watch(() => state.count, cb)`, so Vue can run the function, see that it reads `state.count`, and re-run it when that property changes.

  2. 02A search box runs `watchEffect(async () => { results.value = await search(query.value, page.value) })`. A colleague moves `page.value` below the `await`. What breaks?

    `watchEffect` only tracks reactive reads that happen synchronously during the run. Anything read after the first `await` happens after Vue has stopped collecting dependencies, so `page` would no longer be tracked and changing the page would not re-run the search. Read every dependency before the first `await`, or switch to `watch([query, page], ...)`, which names its sources explicitly.

  3. 03The user types quickly and an older, slower search response arrives after a newer one, overwriting fresh results with stale ones. How do watchers help fix this?

    Register a cleanup function in the watcher. Vue calls it right before the watcher runs again, and when the watcher is stopped. In it, abort the previous request (for example with an `AbortController`) or set a flag that makes the old response ignore itself. In Vue 3.5+ call `onWatcherCleanup(() => controller.abort())` synchronously inside the watcher; in earlier versions use the `onCleanup` argument passed to the callback.

  4. 04When should you prefer `computed` over a watcher that sets a ref?

    Whenever the goal is to produce a value from other state. `watch(a, v => { b.value = v * 2 })` is a hand-rolled computed: it duplicates state, can be briefly out of sync, and runs eagerly. `const b = computed(() => a.value * 2)` expresses the same relationship, is cached and lazy, and cannot drift. Watchers are for effects outside the component's own state.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark