intermediate
useEffect
Synchronize with external systems while managing dependencies, cleanup, and Strict Mode replays.
Effects run after paint to synchronize React with external systems: subscriptions, timers, manual DOM APIs, or logging. They are not the right place to compute derived data that belongs in render. The dependency array controls when the effect re-runs; omitting it runs after every render.
Return a cleanup function to unsubscribe, clear timers, or abort requests. In Strict Mode development, effects mount, clean up, and remount to surface missing cleanup. Async work inside effects should handle races with abort flags or ignore stale responses.
useEffect(() => {
const id = setInterval(tick, 1000);
return () => clearInterval(id);
}, [tick]);
On interviews, explain the concept with a concrete example and name the behavior interviewers probe.
Common pitfalls include hiding data flow, over-splitting components, and putting side effects in render.
The trade-off is often clarity versus reuse or explicit props versus convenience.
Checklist:
- Effects sync externals, not pure derivation.
- List every reactive value in dependencies.
- Always clean up subscriptions and timers.