Skip to content
UniCircle
GuideEngineeringB.Tech / B.E., BCA, MCA

React useEffect: when it runs and how to clean up

What the dependency array really controls, why effects run twice in development, how to clean up timers and subscriptions, and when you do not need an effect at all.

By UniCircle team2 min readPublished 22 Oct 2026Undergraduate

An effect lets a component stay in sync with something outside React: a timer, a network request, a browser API. It runs after React has updated the screen.

The dependency array decides when

  • useEffect(fn) with no array: after every render.
  • useEffect(fn, []): once, after the first render.
  • useEffect(fn, [roomId]): after the first render and again whenever roomId changes.

Put every value from the component that the effect reads in the array. The React linter rule react-hooks/exhaustive-deps catches the ones you miss.

Cleaning up

Return a function from the effect to undo it. React calls it before running the effect again and when the component disappears.

JSX
function Countdown({ from }) {
  const [left, setLeft] = useState(from);
  useEffect(() => {
    const id = setInterval(() => setLeft(n => (n > 0 ? n - 1 : 0)), 1000);
    return () => clearInterval(id);
  }, []);
  return <p>{left === 0 ? 'Time is up' : `${left} seconds left`}</p>;
}
render(<Countdown from={30} />);
text
<p>30 seconds left</p>

Without the cleanup, every remount would start another interval and the countdown would speed up.

Why effects run twice in development

In development with Strict Mode, React mounts, unmounts and mounts each component again to check that your cleanup works. If something breaks when that happens, the effect is missing a cleanup. Production runs it once.

When you do not need an effect

  • Calculating a value from props or state, such as a filtered list: compute it during render.
  • Responding to a click: do it in the event handler.
  • Copying props into state just to display them: use the prop directly.

#react#useeffect#hooks#cleanup

Sources and further reading

Practise this as an interview question

Written by the UniCircle team, checked by an editor on 22 Oct 2026. It is not official policy of any university. Exam patterns and rules change; confirm dates and rules on the official website.

Keep reading