Effects and Synchronisation
Use useEffect to sync with systems outside React, and learn when you do not need an effect at all.
Intermediate · about 5 hours · difficulty 4/5
Learn first: Hooks, Refs and State Patterns, The Event Loop
useEffect is the most misused hook. Its real purpose is narrow: synchronise a component with something outside React such as a subscription, a timer, a browser API, a third-party widget or a network connection.
How effects work
- The effect runs after React commits the render to the screen.
- The dependency array lists every reactive value the effect uses. React re-runs the effect when any of them changes. The lint rule tells you what is missing; do not silence it.
- The cleanup function you return runs before the next run and on unmount: unsubscribe, clear timers, abort fetches.
- In development with Strict Mode, React mounts, unmounts and remounts components once to expose missing cleanup. If that breaks your code, your cleanup is wrong.
You might not need an effect
- Derived data: compute it during render (
const visible = items.filter(...)) instead of syncing a second state with an effect. - Responding to events: put logic in the event handler, not in an effect that watches state.
- Resetting state when a prop changes: give the component a
key. - Fetching data: prefer a data library (TanStack Query) or your framework's loaders. Hand-written fetch effects need abort handling and race-condition protection.
Pitfalls
Infinite loops from setting state the effect depends on; objects and functions in dependencies that change every render; stale closures from missing dependencies.
Good enough to move on
You can write an effect with correct dependencies and cleanup (for example a WebSocket or resize listener), and you can spot and remove unnecessary effects in existing code.
Key concepts
- When effects run
- Dependency arrays
- Cleanup functions
- Strict Mode double invocation
- Removing unnecessary effects
- Race conditions and AbortController
- useLayoutEffect
- useSyncExternalStore
Mini project
Build a live search box that fetches results as you type with debouncing, cancels stale requests with AbortController, and subscribes to online/offline events with proper cleanup.
Check yourself
A component copies a prop into state with an effect so it can show a filtered list. What is the simpler, bug-free alternative?
Free resources
- Synchronizing with Effects (react.dev)
- You Might Not Need an Effect (react.dev)
- Lifecycle of Reactive Effects (react.dev)