Question presented to candidate:
"Vue 3 gives you both watch and watchEffect. What is the actual difference between them, and how do you choose? Talk me through a case where watchEffect surprises people."
What a strong answer should cover:
watch(source, cb)tracks only the declared source (a ref, a getter, a reactive object or an array of these) and callscb(newValue, oldValue).watchEffect(fn)has no source list: it runsfnimmediately and tracks every reactive read made during that run, re-collecting dependencies on each run.watchis lazy by default (immediate: truechanges that);watchEffectis always eager. Onlywatchgives you the old value.- With
watchEffect, only reads before the firstawaitare tracked, and conditional branches only track what actually ran. - Both return a handle to stop them (plus
pause/resumesince 3.5) and both are stopped automatically with the component. - Choose
watchwhen you need precise control or the old value;watchEffectwhen the effect reads several values and should simply re-run when any of them change.
Clarifying questions expected:
- "Does the side effect need the previous value, or just the current state?"
- "Is the work async? That changes what
watchEffectcan track."
Code / implementation expected: Yes β the same pair of refs observed with watch and with watchEffect, logging when each runs.