What does the immediate parameter do?
The immediate parameter in the watch() function makes the watcher run its callback right away when it is created, not only on the first change of the observed value.
In simpler terms:
immediate: trueruns the handler right away, as soon as the watcher is set up.
Without immediate, the watcher fires only when the value changes.
A simple example
watch(
count,
(newVal, oldVal) => {
console.log('watch fired', newVal, oldVal)
},
{ immediate: true }
)If count = ref(5):
It fires immediately:
watch fired 5 undefined
Then, on every subsequent change.
Example without immediate (default behavior)
watch(count, () => console.log('changed'))If the user has not changed anything yet:
- the callback does NOT run
- the watcher waits for the first change
This can be inconvenient, for example, when loading data.
When should you use immediate?
1. To load data on initialization
The most common case:
watch(
() => route.params.id,
(id) => loadUser(id),
{ immediate: true }
)It fires right away, without needing to duplicate code in mounted().
2. To sync with localStorage
watch(
form,
() => localStorage.setItem('form', JSON.stringify(form)),
{ immediate: true, deep: true }
)On initialization, it saves the data immediately.
3. To run code that must fire right away and on changes
For example:
- a websocket subscription
- initializing filters
- initial validation
Important nuances
1. With immediate, oldValue is undefined
Since the watcher is starting for the first time, there is no previous value.
2. immediate is not always needed
If the logic should run only on change, immediate is not needed.
3. Use it together with deep if the object is nested
watch(settings, save, { immediate: true, deep: true })Summary (great for interviews)
immediate: truemakeswatch()run its callback right after the watcher is set up. Useful for loading data, initial setup, synchronization, and cases where the effect must run right away instead of waiting for the value to change.
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.