💚 Vue.js Intermediate

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

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.