Sub topic 9
Loading Data Without Race Conditions
This chapter assumes you know useState and useEffect, can read promise chains, and have read the earlier chapters on effect cleanup and dependency arrays.
The problem
A component that loads data by url can send a second request before the first one finishes. Responses do not always arrive in the order the requests were sent. If the slow, older response arrives last, it overwrites the newer one, and the screen shows data for the wrong url. This is a race condition.
A hook that handles it
Each run of an effect has its own closure. The cleanup function of the previous run executes before the next run starts. You can use that to mark the older run as outdated.
import { useState, useEffect } from 'react';
export function useFetchJson(url) {
const [state, setState] = useState({ status: 'loading', data: null, error: null });
useEffect(() => {
let ignore = false;
const controller = new AbortController();
setState({ status: 'loading', data: null, error: null });
fetch(url, { signal: controller.signal })
.then((res) => {
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.json();
})
.then((data) => {
if (!ignore) setState({ status: 'success', data, error: null });
})
.catch((error) => {
if (!ignore && error.name !== 'AbortError') {
setState({ status: 'error', data: null, error });
}
});
return () => {
ignore = true;
controller.abort();
};
}, [url]);
return state;
}How it works
Two separate guards protect the state.
- The
ignoreflag is local to one effect run. Whenurlchanges, React runs the cleanup of the old run first, which sets that run'signoretotrue. If the old response still arrives, its.thensees the flag and does not callsetState. - The
AbortControllercancels the network request itself. The browser stops waiting and thefetchpromise rejects with anAbortError. Thecatchskips that error, because an abort is expected and is not a failure to show the user.
The flag is the part that guarantees correctness. Not every async source can be aborted, but you can always ignore its result. Aborting saves bandwidth. Cleanup on unmount uses the same two guards, so you also avoid updating state on a component that is gone.
Design choices
- One state object.
status,dataanderrorchange together, so a singlesetStatecall avoids a render wherestatusissuccessbutdatais stillnull. - A reset at the start. Setting
status: 'loading'and clearingdatawhenurlchanges stops the old data from being shown under the new URL. If you prefer to keep showing stale data during a reload, keepdataand change onlystatus. - Check
res.ok.fetchresolves on HTTP 404 and 500. Without the check, an error page would be passed tores.json()and fail with a confusing parse error.
Using it is simple:
function UserCard({ id }) {
const { status, data, error } = useFetchJson(`/api/users/${id}`);
if (status === 'loading') return <p>Loading…</p>;
if (status === 'error') return <p>Failed: {error.message}</p>;
return <h2>{data.name}</h2>;
}For production apps, a library such as TanStack Query or SWR adds caching, retries and deduplication. Writing the hook yourself shows what those libraries do internally.
Exercise
In useFetchJson, the url changes from /a to /b while /a is still loading. Which two things happen in the cleanup of the first effect run, and what does each one prevent?
Show answer
Cleanup sets ignore = true, which stops the late response for /a from calling setState and overwriting the result for /b. It also calls controller.abort(), which cancels the in-flight request for /a so the browser stops downloading it. The catch ignores the resulting AbortError.