Learn Watchers in Vue

A watcher runs side effects (work other than calculating a value to display, such as writing to the console or saving data) when reactive data changes, while…

A customer raises the iced tea order to 3, then reloads the page by accident. The cart goes back to 1. To keep the number, every time count changes it has to be copied into localStorage (storage in the browser that keeps its contents when the page reloads). Copying a number is not calculating a value to display, so a computed doesn't fit.

What fits is a watcher: a function Vue runs every time a particular piece of reactive data changes. It is for side effects: work other than calculating a value to display. Examples are saving the cart to localStorage, writing to the console, or calling a server. Picture Mrs. Sri telling a waiter: "Every time the order number on the board changes, copy it into the notebook." The waiter doesn't calculate anything. He only waits for the board to change, then acts. In Vue, the board is reactive data, the waiter is a watcher, and copying into the notebook is the side effect.

watch(): runs when its source changes

In this code, a watcher watches count and saves it to localStorage every time it changes:

const count = ref(Number(localStorage.getItem("count") ?? 1))

watch(count, (newVal, oldVal) => {
  localStorage.setItem("count", newVal)
  console.log("Saved:", oldVal, "→", newVal)
})

---template---
<p>Iced Tea × {{ count }} · ${{ count * 5 }}</p>
<button @click="count++">+1 portion</button>
Event count Console localStorage "count"
Page shows 1 (empty) (nothing yet)
Click +1 portion 2 Saved: 1 → 2 "2"
Click +1 portion 3 Saved: 2 → 3 "3"
Reload the page 3 (empty) "3"

The first exercise uses the same pattern: watch(count, (newVal) => { console.log("Count:", newVal) }). Click the button once: the number becomes 1, and the console writes Count: 1. The second exercise watches status from a <select> and uses its old value: if the choice changes from Open to Closed, the paragraph becomes Open to Closed.

watch or computed?

computed watch
What it's for computing a value to display doing something when data changes
Returns a value (a read-only ref) no value for the template
Stall example total = computed(() => count.value * 5) saving count to localStorage

A practical rule: if the result is meant to be shown, use computed. If you want to do something, use a watcher. Text like "Searching: " + query (query holds the search words) is a derived value, so it fits computed. Text that needs the old value, like Open to Closed in the second exercise, can't be made with computed. A computed only knows the current value, while a watch callback receives (newVal, oldVal).

watchEffect(): runs right away and records its own sources

watchEffect is another way to write a watcher. This watcher does the same job as the watch example above:

watchEffect(() => {
  localStorage.setItem("count", count.value)
  console.log("Saved:", count.value)
})
watch watchEffect
Source written explicitly recorded automatically from what is read
First run when the source changes right away, when created
Old value yes no

watch can also run right away with the option { immediate: true }. On that first run, the callback receives oldVal = undefined.

Sources you can watch

Here are three ways to watch a reactive object called cart. save is the callback:

const cart = reactive({ menu: "Iced Tea", count: 1 })

watch(cart.count, save)        // wrong: what gets passed is the number 1
watch(() => cart.count, save)  // right: a getter
watch(cart, save)               // the whole object, deep
Source Example The watcher runs when
ref count count.value changes
getter () => cart.count the function's result changes
reactive object cart any property inside changes, however deep
array of sources [menu, count] one of them changes

A getter here is a function that returns the value to watch. Without a getter, JavaScript reads cart.count before watch is called. So all watch gets is the number 1, not reactive data. A number can't change, so the watcher never runs, and localStorage stays empty even though the screen already says 3. The production build shows no message at all. In development mode, the console writes [Vue warn]: Invalid watch source: 1 A watch source can only be a getter/effect function, a ref, a reactive object, or an array of these types. Wrap it in a getter: () => cart.count.

If you watch the whole cart, the watcher is deep automatically: it also watches every property inside, so even changing menu triggers it. But newVal and oldVal are the same object: cart itself, whose contents have already changed. After count goes from 1 to 2, oldVal.count is 2 as well. If you need the old number, watch the getter () => cart.count.

📌 Options and when it runs

⚠️ Watchers that never run, or run when you don't expect

TL;DR: A watcher runs side effects (work other than calculating a value to display, such as writing to the console or saving data) when reactive data changes, while computed calculates a value to display. watch(count, (newVal, oldVal) => { ... }) needs a source written out (the data to watch, here count), is lazy (doesn't run at the start), and gives the new and old values. watchEffect(() => { ... }) records the data it reads and runs once right away. Valid sources: a ref, a getter (a function that returns the value) such as () => cart.count, a reactive object (deep automatically: the properties inside are watched too, but oldVal is the same as newVal), or an array of those. cart.count without a getter is just a number, so the watcher never runs. Key options: immediate (run right away), deep, once (run only once), and flush: "post" to read the updated DOM.

⚡ watch() runs when its source changes

Write:

const count = ref(Number(localStorage.getItem("count") ?? 1))

watch(count, (newVal, oldVal) => {
  localStorage.setItem("count", newVal)
  console.log("Saved:", oldVal, "→", newVal)
})

---template---
<p>Iced Tea × {{ count }} · ${{ count * 5 }}</p>
<button @click="count++">+1 portion</button>
Guess first: the page has just appeared and nothing's been clicked. What does the console print?

Nothing. watch is lazy: it only runs when count really changes. Click +1 portion, and Saved: 1 → 2 appears.

Meaning: watch(count, (newVal, oldVal) => ...) is a watcher: Vue runs the function in the second argument (the callback) every time count, its source, changes. The callback receives the new value, then the old one. A watcher is for side effects: work other than calculating a value to display, such as saving the number to localStorage (storage in the browser that keeps its contents when the page reloads). If the result is meant to be shown, use computed.

⚡ watchEffect records its own sources

Write:

watchEffect(() => {
  localStorage.setItem("count", count.value)
  console.log("Saved:", count.value)
})

Meaning: watch needs a source written out. watchEffect takes just one function and records by itself the reactive data read inside it, here count. watchEffect runs once right away when created, and has no old value.

⚡ A property needs a getter

Write:

watch(() => cart.count, save)
Guess first: cart is a reactive object with count: 1, and save is the callback. If you write watch(cart.count, save), when does the watcher run?

Never. JavaScript reads cart.count before watch is called, so all it gets is the number 1, not reactive data.

Meaning: For one property of a reactive object, wrap it in a getter, a function that returns its value: () => cart.count. save runs every time the getter's result changes.

What you will learn