Sub topic 6
Cleaning up with AbortController
This chapter assumes you know promises and async/await, React components and JSX, useState, and the basics of useEffect and its dependency array. It also assumes you have seen how a fetch inside an effect can return responses out of order. Here you will learn how to cancel an in-flight request when its effect is no longer current.
The problem cleanup solves
When a component fetches data in an effect, the effect can run again before the previous request finishes. This happens when a dependency such as userId changes. It also happens when the component unmounts. The old request keeps going. When it resolves, its .then callback calls setState with data that no longer matches the screen.
Imagine a user clicks through profiles 1, 2, and 3 quickly. Three requests start. If the response for 1 arrives last, the screen shows user 1 while the page says user 3. Cleanup fixes this by cancelling the old request when the effect is replaced.
React runs an effect's cleanup function in two cases:
- Before the effect runs again because a dependency changed.
- When the component unmounts.
Whatever the effect returns is its cleanup function. That is the place to cancel the work the effect started.
AbortController in two parts
AbortController is a browser API, and Node.js also provides it. It has two parts:
controller.signalis anAbortSignal. You pass it tofetchin thesignaloption.controller.abort()marks the signal as aborted. Afetchusing that signal rejects its promise with aDOMExceptionwhosenameis'AbortError'. If the response body is still being read,response.json()rejects the same way.
const controller = new AbortController();
fetch('/api/users/1', { signal: controller.signal })
.then((response) => response.json())
.then((data) => console.log(data))
.catch((error) => console.log(error.name));
controller.abort(); // logs "AbortError"A controller is single use. Once aborted, its signal stays aborted. Each effect run therefore needs its own new controller.
The standard pattern
Here is the pattern in a component. Read it in the order the events happen.
import { useEffect, useState } from 'react';
function UserProfile({ userId }) {
const [user, setUser] = useState(null);
const [error, setError] = useState(null);
const [isLoading, setIsLoading] = useState(true);
useEffect(() => {
const controller = new AbortController();
setIsLoading(true);
setError(null);
fetch(`/api/users/${userId}`, { signal: controller.signal })
.then((response) => {
if (!response.ok) {
throw new Error(`Request failed with status ${response.status}`);
}
return response.json();
})
.then((data) => {
setUser(data);
setIsLoading(false);
})
.catch((err) => {
if (err.name === 'AbortError') return;
setError(err);
setIsLoading(false);
});
return () => controller.abort();
}, [userId]);
if (isLoading) return <p>Loading...</p>;
if (error) return <p>Error: {error.message}</p>;
return <h1>{user.name}</h1>;
}Three details make this correct:
- The controller is created inside the effect, so each run has its own.
- The
catchhandler returns early forAbortError. An abort is expected, not a failure. Without this check, cancelling a request would put an error message on screen. - The cleanup calls
controller.abort(). WhenuserIdchanges from 1 to 2, React calls the cleanup for the run with 1, then starts the run with 2.
The setIsLoading(false) call is absent from the abort branch on purpose. The newer effect run has already set loading to true and owns the state now. If the old run reset it, the screen could briefly show stale or empty content.
What happens over time
The diagram shows the order of events when userId changes while a request is in flight.
Edge cases and gotchas
Aborting does not guarantee the server stops
Aborting closes the client side of the request. The browser stops waiting and may cancel the network transfer. The server may already have received the request and may finish the work. Aborting is safe for reads such as GET. For writes, an aborted POST may still have been applied. This is one reason mutations are usually not tied to effect cleanup.
A response can arrive just before the abort
There is a small window where the response has finished and .then is already queued when cleanup runs. Because the signal is aborted, response.json() usually rejects, so the state update is skipped. If your code uses already-parsed data after an await, check the signal yourself:
useEffect(() => {
const controller = new AbortController();
async function load() {
try {
const response = await fetch(`/api/users/${userId}`, {
signal: controller.signal,
});
if (!response.ok) {
throw new Error(`Request failed with status ${response.status}`);
}
const data = await response.json();
if (controller.signal.aborted) return;
setUser(data);
} catch (err) {
if (err.name === 'AbortError') return;
setError(err);
}
}
load();
return () => controller.abort();
}, [userId]);The signal.aborted check guards any work that does not itself take the signal.
Third-party code may ignore the signal
fetch supports signal, and so do several libraries, including Axios in recent versions. Some wrappers and older clients do not. If you cannot pass a signal, use a boolean flag as a fallback:
useEffect(() => {
let ignore = false;
legacyClient.getUser(userId).then((data) => {
if (!ignore) setUser(data);
});
return () => {
ignore = true;
};
}, [userId]);This stops stale state updates but does not cancel the network request. The request still uses bandwidth and a server connection. Prefer AbortController when the API accepts it.
Check the error by name, not by type alone
The rejection for an aborted fetch is a DOMException with name === 'AbortError'. Do not compare the message text, which differs between browsers. If you call controller.abort(reason) with your own reason, fetch rejects with that reason instead, so the name check no longer matches. Use abort() with no argument unless you also handle the custom reason.
Do not abort from the wrong place
Do not store the controller in state and call abort() from render. Aborting is a side effect, so it belongs in cleanup or an event handler. Also avoid sharing one controller across effect runs. After the first abort, every later request that uses it fails immediately with AbortError.
Timeouts
You can combine cancellation with a time limit using AbortSignal.timeout(ms). This is available in current browsers and Node.js. A timeout rejects with a TimeoutError, not an AbortError, so handle both names if you want to show a message for timeouts.
const signal = AbortSignal.timeout(5000);
fetch('/api/slow', { signal }).catch((err) => {
if (err.name === 'TimeoutError') console.log('Timed out');
});To combine a timeout with cleanup, use AbortSignal.any([controller.signal, AbortSignal.timeout(5000)]). Check browser support first, because any is newer.
Common mistakes
| Mistake | Effect | Fix |
|---|---|---|
| Creating the controller outside the effect | After one abort, later requests fail instantly | Create a new controller in each effect run |
| Treating `AbortError` as a failure | Error message appears when the user navigates or changes input | Return early in `catch` for `AbortError` |
| Forgetting to return the cleanup | Stale responses still update state | Return `() => controller.abort()` |
| Passing no `signal` to `fetch` | Abort has no effect | Pass `{ signal: controller.signal }` |
| Using abort for writes | Server may still apply the change | Treat writes as mutations, not effect work |
Cleanup and Strict Mode
In development, Strict Mode runs each effect, then its cleanup, then the effect again. With the pattern above, the first request is aborted and the second completes. You may see one cancelled request in the network tab. This is expected and confirms that your cleanup works. The next chapter covers this behavior in more detail.
Exercise
A component fetches /api/search?q=${query} in an effect with [query] as dependencies. The effect creates one AbortController at module level (outside the component) and calls controller.abort() in cleanup. The first search works, but after the user changes the query, every later search shows an error or nothing. Why does this happen, and how do you fix it?
Show answer
An aborted controller stays aborted. After the first cleanup calls abort(), the shared controller's signal is aborted permanently, so every later fetch using it rejects immediately with AbortError, which the code either shows as an error or ignores. The fix is to create new AbortController() inside the effect so each run gets its own, and to return early from catch when err.name === 'AbortError'.
Exercise
Your effect calls a third-party client whose getUser(id) function takes no signal option. How do you prevent a stale response from calling setUser, and what does this approach not do?
Show answer
Declare let ignore = false inside the effect, check if (!ignore) before calling setUser in the .then callback, and set ignore = true in the cleanup function. This prevents stale state updates, but it does not cancel the request, so the network call still completes and uses bandwidth and a server connection.