ReactEasy

What is the cleanup function in useEffect?

The cleanup function is the function you return from an effect's setup. React calls it before running the effect again (with the previous render's values) and when the component unmounts. Use it to undo what the setup did: unsubscribe, remove listeners, clear timers, close connections and abort requests.

When it runs

  1. Component mounts: setup runs.
  2. A dependency changes: cleanup (old values), then setup (new values).
  3. Component unmounts: cleanup.
  4. In development Strict Mode, an extra setup, cleanup, setup cycle runs on mount to check that cleanup is symmetrical.
  5. With React 19.2's <Activity mode="hidden">, cleanups run when the content is hidden and setups run again when it becomes visible.

What to clean up

  • addEventListener with removeEventListener.
  • setInterval/setTimeout with clearInterval/clearTimeout.
  • new WebSocket() / EventSource with .close().
  • fetch with AbortController.abort(), or an ignore flag to drop stale responses.
  • Observers (IntersectionObserver, ResizeObserver) with .disconnect().
  • Third-party widgets with their destroy() method.

Why it matters

Missing cleanup causes memory leaks, duplicate subscriptions, state updates on unmounted components, and race conditions where an old response overwrites a newer one.

Related: ref cleanup (React 19)

Callback refs can return a cleanup function too: ref={(node) => { observe(node); return () => unobserve(node); }}.

Code example

tsx
1import { useEffect, useState } from "react";
2
3export function Ticker({ symbol }: { symbol: string }) {
4 const [price, setPrice] = useState<number | null>(null);
5 const [seconds, setSeconds] = useState(0);
6
7 useEffect(() => {
8 const controller = new AbortController();
9 fetch(`/api/quote/${symbol}`, { signal: controller.signal })
10 .then((r) => r.json())
11 .then((q: { price: number }) => setPrice(q.price))
12 .catch((err) => {
13 if (err.name !== "AbortError") console.error(err);
14 });
15
16 const id = setInterval(() => setSeconds((s) => s + 1), 1000);
17
18 return () => {
19 controller.abort(); // cancel the request for the previous symbol
20 clearInterval(id); // stop the timer
21 setSeconds(0);
22 };
23 }, [symbol]);
24
25 return <p>{symbol}: {price ?? "…"} (watching {seconds}s)</p>;
26}

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React set.

Open in study app