Skip to main content

What is watch?

watch is a Vue tool that lets you react to state changes: run code when the value of a ref, reactive, computed, or even props changes.

In simple terms:

watch is a "watcher" that observes data and runs a function when it changes.


A simple example

javascript
<script setup> import { ref, watch } from 'vue' const count = ref(0) watch(count, (newValue, oldValue) => { console.log("count changed:", oldValue, "→", newValue) }) </script>

When count.value++ runs, watch fires.


What is watch for?

watch is used for side effects, for example:

  • send a request when a parameter changes
  • start a timer
  • save data to localStorage
  • track changes to props
  • react to user input
  • run heavy logic without blocking the UI
  • debounce a search

watch is NOT for displaying data in the UI (that is what computed and template output are for).


watch syntax

1) Watch a single value

javascript
watch(source, callback)

2) Watching a ref

javascript
watch(count, (newVal, oldVal) => { console.log(newVal) })

3) Watching a reactive object

To watch the whole object, you need to use:

javascript
watch(user, (newValue, oldValue) => { console.log("user changed", newValue) })

But there is an important nuance here, deep watching: Vue does not track nested fields by default, you need to specify { deep: true }.


4) Watching a specific reactive property

Correct:

javascript
watch(() => user.age, (newVal) => { console.log("Age changed:", newVal) })

5) Multiple sources

javascript
watch([firstName, lastName], ([newF, newL]) => { console.log("First or last name changed") })

Important watch options

1) { immediate: true }

Run the watcher immediately:

javascript
watch(count, callback, { immediate: true })

2) { deep: true }

For watching nested objects:

javascript
watch(user, callback, { deep: true })

3) Cleaning up effects (onCleanup)

javascript
watch(id, (newId, _, onCleanup) => { const controller = new AbortController() fetch(`/api/${newId}`, { signal: controller.signal }) onCleanup(() => controller.abort()) })

Used when canceling requests, timers, and subscriptions.


Difference between watch and computed

Taskcomputedwatch
Get a derived valueYesNo
React to a changeNot for thisYes
Side effectsNot allowedAllowed
CachingYesNo

Example: sending a request on input

javascript
<script setup> import { ref, watch } from 'vue' const query = ref("") watch(query, async (newQuery) => { const data = await fetch(`/search?q=${newQuery}`).then(r => r.json()) console.log(data) }) </script>

Summary (in short)

watch is a reactive watcher that runs a function every time the selected data changes.

It is used for:

  • side effects,
  • requests,
  • timers,
  • synchronizing external services,
  • working with localStorage,
  • debouncing and complex logic.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.