Sub topic 6
Cleaning up with AbortController
This chapter assumes you know useEffect and its dependency array, useState, promises, and the fetch response checks from earlier chapters. It also assumes you have seen the race condition that happens when an input changes while a request is still running.
The problem cleanup solves
When userId changes, React runs the effect again. The earlier request may still be in flight. If it finishes after the newer one, it calls setUser with old data. The screen then shows the wrong user.
React gives every effect a chance to undo its work. The function you return from useEffect is the cleanup function. React calls it before the next run of the effect and when the component unmounts.
What AbortController does
An AbortController is a browser object that can cancel a fetch. It has two parts:
controller.signalis an object you pass tofetchin the options.controller.abort()tells the signal to cancel the request.
When a request is aborted, the promise returned by fetch rejects with an error whose name is AbortError. The browser also stops the network transfer where it can.
Putting it in an effect
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>;
}Follow what happens when userId goes from 1 to 2:
- React calls the cleanup from the first run, which aborts the request for user 1.
- That request's promise rejects with
AbortError. - The
catchblock sees the name and returns without touching state. - React runs the effect again and starts the request for user 2.
Why the AbortError check matters
An abort is an expected event, not a failure. Without the if (err.name === 'AbortError') return; line, the catch block would set an error and flip isLoading to false. The user would see an error message, or a flash of one, every time the input changed.
Also notice that the abort path skips setIsLoading(false). This is correct. The newer effect run has already set loading to true and owns the state from then on.
Limits to know
- Aborting cancels the request on the client. The server may still receive it and do the work. Do not rely on abort to stop a side effect on the server.
- A request can finish just before cleanup runs. Its
.thenhandlers may already be queued. In practice the abort rejects the pendingresponse.json()as well, so stale data rarely gets through. If you use a library that ignores signals, use anignoreflag set in cleanup instead. abort()on a request that has already finished has no effect, so calling it in cleanup is always safe.
Exercise
In the effect above, what would go wrong if you removed the if (err.name === 'AbortError') return; line, and the user switched quickly from user 1 to user 2?
Show answer
Cleanup aborts the request for user 1, and its promise rejects with an AbortError. Without the check, the catch block would call setError and setIsLoading(false). The component would show an error message, or stop showing the loading state, even though the request for user 2 is still running and nothing actually failed.
Exercise
A teammate writes const controller = new AbortController(); and returns () => controller.abort() from the effect, but calls fetch(url) without any options. Does switching inputs cancel the old request? Why or why not?
Show answer
No. The controller is not connected to the request unless its signal is passed as fetch(url, { signal: controller.signal }). Calling abort() then only changes the signal, which nothing is listening to.