Senior
What is the difference between watch and watchEffect in Vue.js?
sobes.tech AI
Answer from AI
In Vue.js, watch and watchEffect are used to observe changes in reactive data but have different scenarios and features.
-
watch — allows observing specific reactive properties or functions and executing a callback when they change. Suitable when you need to react to a specific value change.
-
watchEffect — automatically tracks all reactive dependencies used inside its function and re-executes the function when any of them change. This is a more declarative and automatic way of tracking reactivity.
Example:
import { ref, watch, watchEffect } from 'vue';
const count = ref(0);
// watch — monitors count and calls the callback on change
watch(count, (newVal, oldVal) => {
console.log(`count changed from ${oldVal} to ${newVal}`);
});
// watchEffect — automatically tracks all reactive dependencies inside the function
watchEffect(() => {
console.log(`count is now: ${count.value}`);
});
Key difference:
watchrequires explicitly specifying what to observe.watchEffectautomatically tracks all reactive data used inside the function.
watch is useful when you need to react to specific changes with access to old and new values, while watchEffect is for automatically reacting to any changes in reactive data inside the effect.