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 Array | When Effect Runs |
|---|---|
[] (empty) | Once on mount, cleanup on unmount |
[a, b] | When a or b changes |
| No array | Every render (usually wrong) |
Common Use Cases
| Use Case | Dependencies |
|---|---|
| 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
| Pitfall | Fix |
|---|---|
| Infinite loop | Missing/wrong dependency array |
| Stale closure | Use updater function or add dependency |
| Missing cleanup | Always cleanup subscriptions, intervals, abort controllers |
| Race condition | Use AbortController or ignore flag for async fetches |
File
use-effect.tsxβ mount/cleanup, fetch data, abort controller, stale closures, timers, event listeners, dependency pitfalls