useEffect: Side Effects

Medium•

The most common effect bugs are stale closures, dependency mismatches, and missing cleanup semantics.

Quick Decision Guide

useEffect is synchronization, not derivation.

Use for: - subscriptions - timers - network and imperative APIs

Interview signal: explain external system, dependency contract, and cleanup guarantees.

Synchronization Mental Model

🔥 Insight

Render computes UI; effects synchronize with external systems.

🧠 Mental Model

render -> commit
effect setup -> external sync
next change/unmount -> cleanup previous sync

Dependency Behavior and Closure Pitfalls

useEffect(() => {
  const controller = new AbortController()
  fetch(url, { signal: controller.signal })
  return () => controller.abort()
}, [url])

Pitfalls

•Missing dependency -> stale captured values
•Extra unstable dependency -> excessive resynchronization
•No cancellation -> race conditions and memory leaks

Rules of Hooks (and why)

•Call hooks at the top level of React components or custom hooks.
•Do not call hooks inside conditions, loops, or nested functions.
•Only call hooks from React function components or other custom hooks.

These rules follow from React's render model:

•React relies on consistent hook call order across renders.
•Hook identity is tied to position in the render sequence.
•Conditional or reordered hook calls can misassociate state/effects and produce incorrect behavior.

Trade-offs, Misuse Patterns, Interview Takeaway

Trade-offs

•Effects centralize integration with external systems
•But poor dependency design makes behavior fragile

Misuse Patterns

•Doing pure transformations in effects
•Triggering state loops with effect-setState cycles

🎯 Interview Takeaway

Say what external system is being synchronized, why each dependency exists, and how cleanup preserves correctness.

Key Takeaways

1Effects are for external synchronization, not pure derivation.
2Dependency arrays are behavioral contracts, not optional hints.
3Cleanup logic is part of correctness.
4Closure awareness is essential in interview-grade effect reasoning.