Skip to main content
13

useEffect: dependencies, cleanup and when not to use it

MediumReactHooksuseEffect

How does useEffect work? Explain the dependency array, cleanup, and when you shouldn't use it.

TL;DR

useEffect runs a side effect after React commits the render to the screen, to synchronize your component with an external system (a subscription, a timer, a non-React widget, the network). The dependency array decides when it re-runs: no array means after every render, [] means once on mount, and [a, b] means whenever a or b change. The returned cleanup function runs before the effect re-runs and on unmount.

Key points

  • List every reactive value the effect reads (props, state, functions defined in the component). The react-hooks/exhaustive-deps lint rule enforces this.
  • Cleanup undoes the effect: unsubscribe, clearInterval, abort a fetch.
  • In Strict Mode during development, React runs mount → cleanup → mount to surface missing cleanups.
  • You don't need an effect to compute values from props or state (compute during render), to respond to a user event (do it in the handler), or to reset state on a prop change (use a key).
  • For data fetching, prefer a library (TanStack Query) or your framework's loader; raw effects need race-condition handling.

Example

jsx
useEffect(() => {
  const controller = new AbortController()
  fetch(`/api/users/${userId}`, { signal: controller.signal })
    .then((r) => r.json())
    .then(setUser)
    .catch(() => {})
  return () => controller.abort() // ignore stale responses when userId changes
}, [userId])

// Not an effect: derived value
const fullName = `${first} ${last}`

Common follow-ups

  • useEffect vs useLayoutEffect? useLayoutEffect runs before the browser paints. Use it only to measure layout and avoid a visible flicker.
  • Why does my effect loop forever? It sets state that's in its own dependencies, or depends on an object or function recreated every render.

What interviewers look for

Tip

"Effects synchronize with external systems." Then show cleanup, correct dependencies, and examples where an effect is the wrong tool.

  • Red flag: using effects to copy props into state or to chain state updates.

Was this helpful?

Related questions