💚 Vue.js Intermediate

What is Vue's reactivity with watchEffect and its nuances?

Why Interviewers Ask This

This question targets practical, hands-on experience with Vue.js. Interviewers want to see if you've worked with these concepts in real projects, not just read about them. Strong answers include concrete examples.

Answer

watchEffect automatically tracks its reactive dependencies (like computed) but runs as a side-effect (like watch) — it re-runs the callback whenever any reactive values it reads change. Key behaviors: (1) Immediate: runs once immediately when first called (no immediate: true needed like watch); (2) Auto-tracking: any reactive value (ref, reactive, computed, route, store) accessed inside the callback is automatically tracked; (3) Re-runs on any dependency change; (4) Cleanup: return a cleanup function from the callback for teardown between runs: watchEffect((onCleanup) => { const timer = setTimeout(() => { fetchData(id.value); }, 300); onCleanup(() => clearTimeout(timer)); });. Timing options: { flush: "post" } — run after component DOM update (access updated DOM), equivalent to watchPostEffect(); { flush: "sync" } — synchronous, fires immediately on every change (use rarely); default: "pre" — before component re-renders. watchPostEffect: alias for watchEffect with { flush: "post" } — useful for accessing updated DOM or child component state. watchSyncEffect: alias for { flush: "sync" }. Stopping: const stop = watchEffect(() => {}); stop(); — auto-stopped when component unmounts if called in setup. If called outside setup(), must be stopped manually. watchEffect vs watch: watchEffect doesn't give old/new values; watch is more explicit about what to watch; watchEffect is simpler for multiple dependencies.

Pro Tip

This topic has Vue.js-specific nuances that differ from general programming. Highlighting those nuances in your answer shows expertise rather than generic knowledge.