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
- Component mounts: setup runs.
- A dependency changes: cleanup (old values), then setup (new values).
- Component unmounts: cleanup.
- In development Strict Mode, an extra setup, cleanup, setup cycle runs on mount to check that cleanup is symmetrical.
- 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
addEventListenerwithremoveEventListener.setInterval/setTimeoutwithclearInterval/clearTimeout.new WebSocket()/EventSourcewith.close().fetchwithAbortController.abort(), or anignoreflag 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";23export function Ticker({ symbol }: { symbol: string }) {4 const [price, setPrice] = useState<number | null>(null);5 const [seconds, setSeconds] = useState(0);67 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 });1516 const id = setInterval(() => setSeconds((s) => s + 1), 1000);1718 return () => {19 controller.abort(); // cancel the request for the previous symbol20 clearInterval(id); // stop the timer21 setSeconds(0);22 };23 }, [symbol]);2425 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.