Sub topic 5
Cleanup: undoing what an effect started
This chapter assumes you know function components, useState, closures, and the basics of useEffect and its dependency array. Here you will learn how to undo what an effect started.
Why cleanup exists
Some effects start something that keeps running: an event listener, a timer, a network request. If you never stop it, it outlives the render that created it. The result is a leak, or a callback that updates state after the component is gone.
An effect can return a function. React calls that function the cleanup. It is your chance to undo the setup.
When cleanup runs
React runs cleanup in two situations:
- Before it re-runs the effect, when a dependency changed. The cleanup from the previous render runs first, using the values from that previous render.
- When the component unmounts.
Cleanup does not run after the first render, because there is nothing to undo yet.
Example: a resize listener
The effect adds a listener. The cleanup removes it.
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;
}Without the returned function, each mount would add another listener and none would be removed. The cleanup must remove the same function that was added, so handleResize is declared once inside the effect and both calls use it.
Example: ignoring an outdated request
Cleanup also protects against stale results. Suppose userId changes quickly. A slow response for the old user could arrive after the response for the new one and overwrite it.
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 calls controller.abort() for the old request. The old fetch rejects with an AbortError, and the catch ignores it. Only the latest request can set state.
The rule: cleanup mirrors setup
Ask what the effect started, then write the matching undo.
| Setup | Cleanup |
|---|---|
| `addEventListener` | `removeEventListener` |
| `setInterval` or `setTimeout` | `clearInterval` or `clearTimeout` |
| `fetch` with a signal | `controller.abort()` |
| Opening a connection or subscription | Closing or unsubscribing |
Common mistakes
- Forgetting to return the cleanup, so listeners pile up with every re-run.
- Removing a different function than the one added, for example by passing a new inline arrow function to
removeEventListener. - Treating
AbortErroras a real failure and showing an error message. - Putting an empty array on an effect that depends on props, so cleanup never runs when those props change.
Exercise
A component runs useEffect(() => { const id = setInterval(tick, 1000); }, []); with no return value. What goes wrong when the component unmounts, and how do you fix it?
Show answer
The interval keeps running after unmount, so tick keeps firing and may try to update state on a component that no longer exists. Return a cleanup function: return () => clearInterval(id);.
Exercise
A useEffect depends on [roomId] and opens a connection to that room. The user switches from room "a" to room "b". In what order do setup and cleanup run, and which room's values does the cleanup see?
Show answer
React first runs the cleanup from the previous render, which sees room "a" and closes that connection. Then it runs the effect again with room "b" and opens the new connection.