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" |
watch(source, callback): the first argument, the source, is the data to watch. The second is the callback, the function that runs every time the source changes.- The callback receives the new value and then the old value. You can choose the parameter names:
(newVal, oldVal)or(next, prev). watchis lazy: when the page first shows, the watcher stays quiet. It only runs whencountreally changes. Setting the same value (count.value = 3when it is already 3) doesn't trigger it either.localStoragestores text, so the number 2 is saved as"2". That's why the starting value is read withNumber(...), and?? 1gives 1 when nothing is saved yet. Thanks to this watcher, the reloaded page still shows 3 portions.- In a real project, import first:
import { ref, watch } from "vue". In the exercise editor everything is already available.
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)
})
watchEffecttakes just one function. You don't write a source: Vue records by itself which reactive data is read inside that function, herecount.watchEffectruns once right away when it is created, then again every time the data it read changes. When the page shows, the console immediately writesSaved: 1.- There is no old value. If you need the previous number, use
watch.
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
{ immediate: true }: runs once when created, likewatchEffect.{ once: true }(Vue 3.4+): runs only once, then stops.{ deep: true }: for a ref holding an object.watch(ref({ count: 1 }), ...)withoutdeeponly runs when the object is replaced, not whencountinside it changes. Since Vue 3.5,deepmay be a number:deep: 1watches only the first level of properties, so a change at the second level, such asorder.value.items.count, doesn't trigger it.{ flush: "post" }: by default the callback runs before Vue updates the DOM. Saycountgoes from 1 to 2, and the callback reads<p id="j">, which showscount. It still reads the old number,1. Withflush: "post", it reads2.watchandwatchEffectreturn a stop function:const stop = watch(...), thenstop(). A watcher created in a component's setup stops by itself when the component is removed.- The callback also receives a third argument,
onCleanup, to tidy up unfinished work before the next callback runs. The Fetching Data lesson uses it for stale requests (old requests whose answer is no longer needed). Vue 3.5 addedonWatcherCleanup()for the same job. But ifonWatcherCleanup()is called after anawait, it isn't registered, and in development mode the console writes[Vue warn] onWatcherCleanup() was called when there was no active watcher to associate with.So an async callback still usesonCleanup.
⚠️ Watchers that never run, or run when you don't expect
- Watching a property without a getter.
watch(cart.count, ...)never runs. Writewatch(() => cart.count, ...). - Expecting
watchto run at the start.watchis lazy. If it must run from the moment the page shows, give it{ immediate: true }or usewatchEffect. - Building the text outside the callback. Text built from the source outside the callback is built only once, so it doesn't change. Build it inside the callback, from the new value it receives.
- Using watch for a value you could compute. If the result is only for display and can be calculated from the current value, computed is shorter. A watcher is for side effects, like the log in the first exercise, or for something that needs the old value, like the second exercise.
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.