TechnicalMedium React

How does the useEffect dependency array work, and why do we return a cleanup function?

Asked for Frontend Developer, Full-Stack Developer, Mobile Developer

Why they ask this: Most React bugs (infinite loops, stale data, memory leaks) come from misusing useEffect.

Answer

useEffect(effect, deps) runs effect after render:

  • No array: runs after every render.
  • []: runs once after the first render (mount).
  • [a, b]: runs after the first render and again whenever a or b changes (compared with Object.is).

The function you return is the cleanup. It runs before the effect runs again and when the component unmounts. Use it to remove listeners, clear timers and cancel requests.

jsx
useEffect(() => {
  const controller = new AbortController();
  fetch(`/api/jobs?q=${query}`, { signal: controller.signal })
    .then((r) => r.json())
    .then(setJobs)
    .catch(() => {});
  return () => controller.abort(); // cancel the old request when query changes
}, [query]);

Include every value from the component that the effect uses in the array. Missing dependencies cause stale values.

Can you explain this in your own words?

Back to question bank