HomeReact
Chapter 8

08 β€” useEffect & Lifecycle

useEffect lets you synchronize a component with external systems (APIs, DOM, timers, subscriptions). It's the replacement for class lifecycle methods.

Mental Model

useEffect = "synchronize with something external" β€” NOT "run code after render."

useEffect(() => {
  // SETUP: runs after render
  return () => {
    // CLEANUP: runs before next effect or unmount
  };
}, [dependencies]);

Dependency Array Rules

Dependency ArrayWhen Effect Runs
[] (empty)Once on mount, cleanup on unmount
[a, b]When a or b changes
No arrayEvery render (usually wrong)

Common Use Cases

Use CaseDependencies
Fetch data on mount[] or [id]
Subscribe to events[]
Sync with prop/state[prop] or [state]
Set document title[title]
Timer/interval[] with cleanup

Common Pitfalls

PitfallFix
Infinite loopMissing/wrong dependency array
Stale closureUse updater function or add dependency
Missing cleanupAlways cleanup subscriptions, intervals, abort controllers
Race conditionUse AbortController or ignore flag for async fetches

File

  • use-effect.tsx β€” mount/cleanup, fetch data, abort controller, stale closures, timers, event listeners, dependency pitfalls