Sub topic 5
Cleanup: undoing what an effect started
This chapter assumes you know function components, useState, closures, and how useEffect and its dependency array decide when an effect runs. It covers the cleanup function: what it is, when React calls it, and the mistakes that cause leaks and stale results.
What a cleanup function is
An effect can return a function. React stores that function and calls it later to undo whatever the effect started. This returned function is the cleanup function.
useEffect(() => {
// setup: start something
return () => {
// cleanup: stop it
};
}, [dependencies]);Cleanup matters because many effects create things that outlive a single render: event listeners, timers, subscriptions, and network requests. If nothing stops them, they keep running after the component no longer needs them. The result is memory leaks, duplicate handlers, and state updates that arrive at the wrong time.
An effect that only reads or writes a value and starts nothing, such as setting document.title, usually needs no cleanup.
When React runs cleanup
React calls cleanup in two situations:
- Before it re-runs the effect, because a dependency changed. The cleanup from the previous run executes first, using the values from that previous render.
- When the component unmounts (is removed from the screen).
Cleanup does not run after the first setup and then wait for the next change. It runs just before the next setup, or at unmount.
Each cleanup function is a closure over the values of the render that created it. When cleanup runs after userId changes from 1 to 2, it still sees userId as 1. This is what lets it undo exactly what that run started.
Worked example: a resize listener
The effect below adds a listener. Without cleanup, each mount would add another listener that is never removed.
import { useEffect, useState } from 'react';
function useWindowWidth() {
const [width, setWidth] = useState(window.innerWidth);
useEffect(() => {
function handleResize() {
setWidth(window.innerWidth);
}
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, []);
return width;
}The cleanup calls removeEventListener with the same function reference that addEventListener received. This is why handleResize is declared as a named function inside the effect. If you passed a fresh inline arrow function to each call, removeEventListener would not match the original and the listener would stay attached.
The empty dependency array means setup runs once on mount and cleanup runs once on unmount.
Worked example: a timer
Timers need the same treatment.
import { useEffect, useState } from 'react';
function Timer() {
const [seconds, setSeconds] = useState(0);
useEffect(() => {
const id = setInterval(() => {
setSeconds((s) => s + 1);
}, 1000);
return () => clearInterval(id);
}, []);
return <p>{seconds} seconds elapsed</p>;
}The interval ID is stored in a local variable inside the effect, and cleanup reads it. Without clearInterval, the interval would keep firing after unmount and call setSeconds on a component that no longer exists.
Worked example: cancelling a request
Cleanup also solves a correctness problem, not only a leak. Suppose userId changes from 1 to 2 while the request for user 1 is still in flight. If the response for user 1 arrives last, it would overwrite the data for user 2. This is a race condition.
import { useEffect, useState } from 'react';
function User({ userId }) {
const [user, setUser] = useState(null);
const [error, setError] = useState(null);
useEffect(() => {
const controller = new AbortController();
setUser(null);
setError(null);
fetch(`/api/users/${userId}`, { signal: controller.signal })
.then((res) => {
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.json();
})
.then(setUser)
.catch((err) => {
if (err.name !== 'AbortError') setError(err);
});
return () => controller.abort();
}, [userId]);
if (error) return <p>Failed to load: {error.message}</p>;
if (!user) return <p>Loading...</p>;
return <h1>{user.name}</h1>;
}When userId changes, React runs controller.abort() for the old request before starting the new one. The aborted fetch rejects with an error whose name is AbortError. The catch ignores that specific error, because an abort here is intentional and not a failure the user should see.
When you cannot abort
Not every async API supports cancellation. In that case, use a flag that marks the result as stale:
import { useEffect, useState } from 'react';
function Profile({ userId }) {
const [profile, setProfile] = useState(null);
useEffect(() => {
let ignore = false;
async function load() {
const res = await fetch(`/api/users/${userId}`);
const data = await res.json();
if (!ignore) setProfile(data);
}
load();
return () => {
ignore = true;
};
}, [userId]);
return profile ? <h1>{profile.name}</h1> : <p>Loading...</p>;
}The request still completes, but its result is discarded if the effect has already been cleaned up. Each effect run has its own ignore variable, so a late response from an old run sees true and does nothing. Prefer AbortController when available, since it also frees the network connection.
Cleanup must mirror setup
A useful rule: cleanup should reverse everything setup did, so that running setup, then cleanup, then setup again leaves the app in the same state as running setup once.
| Setup | Cleanup |
|---|---|
| `addEventListener(type, fn)` | `removeEventListener(type, fn)` |
| `setInterval(fn, ms)` | `clearInterval(id)` |
| `setTimeout(fn, ms)` | `clearTimeout(id)` |
| `fetch(url, { signal })` | `controller.abort()` |
| `socket.connect()` | `socket.disconnect()` |
| `observer.observe(node)` | `observer.disconnect()` |
| `subscribe(callback)` | the unsubscribe function it returned |
This mirror property is what makes your effects safe under Strict Mode, which in development runs setup, cleanup, and setup again on mount to check that cleanup is complete. A later chapter covers that in detail.
Common mistakes
- Forgetting cleanup. Listeners and intervals accumulate. You will see handlers firing multiple times, or a growing number of timers after navigating between screens.
- Cleanup that does not match setup. Removing a different function reference than the one added, or clearing the wrong ID, leaves the original running.
- Reading changing values in cleanup. Cleanup sees the values from the render that created it. That is usually what you want. If you need the latest value of a ref, such as
ref.current, copy it to a local variable inside the effect body first, because the ref may point to something else by the time cleanup runs. - Returning something that is not a function. An effect callback must return nothing or a function. Writing
useEffect(() => fetchData(), [])with an arrow shorthand returns the result offetchData(), which is often a Promise. React warns about this. The same applies to passing anasyncfunction directly touseEffect, because an async function always returns a Promise. Define the async function inside the effect and call it, as in theProfileexample. - Putting cleanup logic in a state update. Cleanup should stop outside activity. Avoid calling
setStatein cleanup to "reset" things, since the component may be unmounting.
Checking your cleanup
A quick test: ask what would happen if the component were mounted and unmounted 100 times. If the answer involves 100 listeners, 100 intervals, or 100 open connections, cleanup is missing or incomplete. In development you can also watch for this in the browser's developer tools, for example by counting listeners or open network requests while navigating between screens.
Exercise
An effect with dependencies [roomId] opens a chat connection with connect(roomId) and returns () => disconnect(). The user switches from room "a" to room "b", then closes the chat screen. In what order do setup and cleanup run from the first mount to the unmount, and which room does each cleanup disconnect?
Show answer
Setup for "a" on mount. When roomId changes to "b", cleanup from the "a" render runs first and disconnects room "a", then setup for "b" runs. When the component unmounts, cleanup from the "b" render runs and disconnects room "b".
Exercise
This effect has a bug: useEffect(() => { window.addEventListener('scroll', () => setY(window.scrollY)); return () => window.removeEventListener('scroll', () => setY(window.scrollY)); }, []); Why does the listener leak, and how do you fix it?
Show answer
The arrow functions passed to addEventListener and removeEventListener are two different function objects, so removeEventListener finds nothing to remove. Declare one named function inside the effect, for example function handleScroll() { setY(window.scrollY); }, and pass that same reference to both calls.