Skip to content
UniCircle
MediumConceptualHooks

useEffect and the dependency array

Question REACT-HKS-002

What is useEffect for? Explain what happens with no dependency array, an empty array, and an array of values. What is the cleanup function, and when does it run?

Show the explanation

Model answer. useEffect runs code after React has updated the screen, to synchronise the component with something outside React: a subscription, a timer, a network request, a browser API.

JSX
useEffect(() => {
  const id = setInterval(() => setSeconds(s => s + 1), 1000);
  return () => clearInterval(id);     // cleanup
}, []);

The dependency array decides when it re-runs:

  • No array: after every render.
  • `[]`: once after the first render (mount); cleanup on unmount.
  • `[a, b]`: after the first render, and again whenever a or b changed (compared with Object.is).

The cleanup function runs before the effect runs again and when the component unmounts. Use it to unsubscribe, clear timers, or cancel requests, so you do not leak memory or set state on an unmounted component.

JSX
useEffect(() => {
  const ctrl = new AbortController();
  fetch(`/api/colleges?q=${query}`, { signal: ctrl.signal }).then(r => r.json()).then(setResults).catch(() => {});
  return () => ctrl.abort();          // a newer query cancels the old request
}, [query]);

Pitfalls: list every value from the component that the effect uses (the lint rule helps); and do not use effects for things computable during render (derived values) or for responding to events (put that in the handler). In development, Strict Mode runs effects twice on mount to expose missing cleanups.

Original UniCircle question. Last reviewed 22 Oct 2026.