What is watch() and how is it used?
Assesses fundamental understanding of Vue.js conventions, runtime behavior, and memory/performance considerations.
Hiring managers look for precision, avoidance of ambiguous jargon, and ability to explain trade-offs under real production conditions.
The watch() function observes a reactive source((like ref, reactive, getter functions or computed values)) and
runs a callback function whenever that source changes.
Syntax:
watch(source, callback, options ?)
- source: a ref, reactive property, getter function, or array of them.
- callback(newValue, oldValue): function to run when the value changes.
- options (optional): object to control behavior (e.g., immediate, deep).
#### Example 1: Watching a ref
import {ref, watch} from 'vue';
const count = ref(0);
watch(count, (newVal, oldVal) => {
console.log(`Count changed from ${oldVal} to ${newVal}`);
});
count.value = 5; // triggers the watch callback
#### Example 2: Watching a function (getter)
const firstName = ref('Sudheer');
const lastName = ref('Jonna');
watch(
() => `${firstName.value} ${lastName.value}`,
(newFullName, oldFullName) => {
console.log(`Full name changed from ${oldFullName} to ${newFullName}`);
}
);
#### Example 3: Watching a reactive object deeply
import {reactive, watch} from 'vue';
const user = reactive({name: 'Sudheer', age: 38});
watch(
() => user,
(newUser, oldUser) => {
console.log('User object changed:', newUser);
},
{deep: true}
);
The main uses of watch() are:
- Watching route changes
- Triggering API calls
- Responding to complex data changes
- Manually reacting to specific state updates
****
Candidate Response Strategy & Interview Tips
- Start with a concise one-sentence summary: Deliver a direct, confident answer first before expanding into nuances.
- Demonstrate real-world trade-offs: Discuss where this approach excels and when you would avoid it in production systems.
- Discuss complexity & edge cases: Proactively explain time/space complexity or boundary conditions (null values, scale limits).
- Prepare for interviewer follow-ups: Technical hiring panels frequently probe deeper into concurrency, backward compatibility, or alternative libraries.