watch and watchEffectConsider a Vue 3 component using both watch and watchEffect. Which statement correctly describes when each watcher runs?
import { ref, watch, watchEffect } from 'vue'; const count = ref(0); const double = ref(0); watch(count, (newVal) => { double.value = newVal * 2; }); watchEffect(() => { console.log(`Count is: ${count.value}`); });
Think about when each watcher first runs and how they track dependencies.
watch runs its callback only when the watched source changes, not immediately by default. watchEffect runs immediately on setup and then reruns whenever any reactive dependency inside it changes.
watchEffect with multiple reactive sourcesWhat will be logged to the console after the following code runs and count.value changes from 1 to 2?
import { ref, watchEffect } from 'vue'; const count = ref(1); const message = ref('hello'); watchEffect(() => { console.log(`Count: ${count.value}, Message: ${message.value}`); }); count.value = 2;
Remember when watchEffect runs its function.
watchEffect runs immediately on setup, logging the initial values. Then it reruns when count.value changes, logging the updated values.
watchWhich option shows the correct way to watch two reactive refs a and b and react when either changes?
import { ref, watch } from 'vue'; const a = ref(0); const b = ref(0);
Think about how to pass multiple sources as an array.
To watch multiple sources, pass an array of refs as the first argument. The callback receives an array of new values.
watchEffect usageWhat error will this code produce when run in a Vue 3 component?
import { ref, watchEffect } from 'vue'; const count = ref(0); watchEffect(() => { count.value++; });
Consider what happens when you change a reactive value inside watchEffect.
Changing count.value inside watchEffect triggers the effect again, causing an infinite loop and stack overflow.
watch over watchEffect for expensive side effects?In Vue 3, why might you choose watch instead of watchEffect when performing expensive operations based on reactive data?
Think about control over when the watcher runs.
watch lets you specify exactly which reactive sources to watch, so you avoid running expensive code unnecessarily. watchEffect runs immediately and reruns whenever any reactive dependency changes, which can cause extra runs.