Middle
What is the difference between watch and watchEffect in Vue?
sobes.tech AI
Answer from AI
In Vue, watch and watchEffect are used to track changes but work differently:
-
watch — observes a specific reactive variable or function. You need to explicitly specify what to track. It allows reacting to changes with access to the old and new values.
-
watchEffect — automatically tracks all reactive dependencies used inside the passed function. It runs immediately and every time any dependency changes. It does not provide the old value.
Example:
import { ref, watch, watchEffect } from 'vue';
const count = ref(0);
// watch
watch(count, (newVal, oldVal) => {
console.log(`count changed from ${oldVal} to ${newVal}`);
});
// watchEffect
watchEffect(() => {
console.log(`count is now: ${count.value}`);
});
watch is suitable when you need to react to a specific change with access to the previous value, watchEffect is for automatic tracking and reactive code execution.