Sub topic 9
Loading data without race conditions
This chapter assumes you know useState and useEffect, promises with fetch, and how a custom hook returns values to a component. It also assumes you have read the earlier chapters on effect cleanup and dependency arrays.
Why data loading goes wrong
Fetching inside an effect looks easy: start a request, then store the result. The bug appears when the inputs change faster than the network answers.
Suppose a component shows a user profile and receives a userId prop. The user clicks "Next" twice quickly. Two requests are now in flight, one for user 1 and one for user 2. Responses do not arrive in the order the requests were sent. If the response for user 1 arrives last, the screen shows user 1's data while the page says user 2. This is a race condition: the final state depends on timing, not on the latest input.
Here is the naive version that has this bug:
import { useState, useEffect } from 'react';
export function useUserBroken(userId) {
const [user, setUser] = useState(null);
useEffect(() => {
fetch(`/api/users/${userId}`)
.then((res) => res.json())
.then((data) => setUser(data)); // runs even if userId has changed
}, [userId]);
return user;
}Every response calls setUser, whether or not it is still relevant. The same mistake causes a second problem: if the component unmounts before the response arrives, the callback still runs and the work is wasted.
The fix: cleanup marks a request as outdated
React runs an effect's cleanup function before it runs the effect again, and when the component unmounts. That gives each effect run a place to say "my result no longer matters."
There are two tools, and the hook below uses both:
- An
ignoreflag. It is a localletvariable scoped to one effect run. Cleanup sets it totrue, and the promise callbacks check it before touching state. This works with any async source, not onlyfetch. - An
AbortController. Callingabort()cancels the network request, so the browser stops downloading a response nobody wants. The pendingfetchpromise rejects with an error namedAbortError.
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;
}Here is how it works, step by step:
- The effect runs when
urlfirst has a value. It creates a freshignoreand a freshcontrollerfor this run only. - It resets the state to
loading, so the component never shows data that belongs to the previous URL. - When
urlchanges, React calls the previous run's cleanup first. That run'signorebecomestrueand its request is aborted. - The new run starts its own request with its own flag. Because each run has a separate
ignorevariable (a closure), a late response from run 1 cannot affect run 2.
Using the hook is a one-liner per call site:
import { useFetchJson } from './useFetchJson';
function UserCard({ userId }) {
const { status, data, error } = useFetchJson(`/api/users/${userId}`);
if (status === 'loading') return <p>Loading…</p>;
if (status === 'error') return <p>Failed: {error.message}</p>;
return <h2>{data.name}</h2>;
}Why both the flag and the abort
It is tempting to keep only one of them. Each covers a gap in the other.
| Mechanism | What it does | What it does not do |
|---|---|---|
| `ignore` flag | Stops stale results from reaching state, for any promise | Does not cancel the network request or other work |
| `AbortController` | Cancels the request and rejects the promise | Cannot stop a response that already arrived and is being processed in `.then` |
A response can finish after abort() has been called but before the promise chain reaches your callback. The flag covers that window. For non-fetch sources such as a database client without abort support, the flag is the only tool you have.
The status object and impossible states
The hook stores status, data and error in a single state object instead of three separate useState calls. Three separate setters can be called one after another and leave an inconsistent combination for a render, such as loading still true while data is already set. A single object updated by one setState call moves between whole, valid states: loading, success, or error.
Consumers also get a clear contract. They branch on status, and data is only meaningful when status is 'success'.
Edge cases you will meet
Errors from non-2xx responses
fetch only rejects on network failure. A 404 or 500 resolves normally. That is why the hook checks res.ok and throws an error itself, which sends it to the catch block. Without that check, res.json() might parse an error page and report success.
Ignoring `AbortError`
Aborting makes the promise reject. That rejection is expected, not a failure. The hook ignores it in two ways: ignore is already true, and the name check filters out AbortError. Keeping the name check is useful if you later remove the flag or reuse the pattern elsewhere.
Strict Mode runs effects twice in development
In development, React Strict Mode mounts, cleans up, and mounts again to expose missing cleanup. With this hook you will see one aborted request followed by one real request in the network panel. That is the correct behavior. If your hook breaks under it, the cleanup is incomplete. A request firing twice in development is not a reason to disable Strict Mode.
Unstable dependencies cause fetch loops
The dependency array is [url]. A string compares by value, so the effect only re-runs when the text changes. If you extend the hook to accept an options object, such as useFetchJson(url, { headers }), a new object created on every render makes the effect re-run on every render, and each run sets state, which triggers another render. Pass primitive values, or memoize the object, as covered in the chapter on dependency arrays.
// Risky: a new object each render, so the effect would re-run every time
// const state = useFetchJson(url, { headers: { Accept: 'application/json' } });
// Safe: depend on primitives
// const state = useFetchJson(url, 'application/json');Resetting state on a new URL
The reset to loading inside the effect avoids showing user 1's data under user 2's heading. It also means that between renders, the first render with the new URL still shows the old state for one frame, because the effect runs after render. If that flash matters, a common alternative is to key the component on the input, so React creates fresh state:
function Profile({ userId }) {
return <UserCard key={userId} userId={userId} />;
}With key, a new userId mounts a new UserCard and a new hook state, so no old data can be shown.
What this hook still lacks
useFetchJson is correct but minimal. It does not cache, deduplicate identical requests from different components, retry failures, or refetch when the window regains focus. Each of those needs shared state outside any single component. For production data loading, a library such as TanStack Query or SWR handles these concerns and the race conditions above. Writing the hook yourself is still valuable. It teaches the cleanup model, and it is a reasonable choice for small apps or one-off endpoints.
Summary of the pattern
- Create
ignoreandAbortControllerinside the effect. - Check
ignorebefore every state update that follows anawaitor.then. - Return a cleanup function that sets the flag and aborts.
- Treat HTTP error statuses as errors yourself.
- Keep the loading, success and error states in one state object.
- Depend on primitive values so the effect runs only when the request truly changes.
Exercise
In useFetchJson, a learner removes the let ignore flag and keeps only controller.abort() in the cleanup. They argue that aborting is enough. Describe one situation in which stale data could still reach state, and name the fix.
Show answer
Abort cancels the request, but a response can already have arrived, and its .then callback can already be queued, at the moment cleanup runs. That callback would still call setState with data for the old URL, so it overwrites the state of the new request. The same happens when the data source does not support abort at all. The fix is to keep the ignore flag, set it to true in cleanup, and check if (!ignore) before every state update.
Exercise
A learner changes the hook to useFetchJson(url, options) and calls it as useFetchJson('/api/items', { method: 'GET' }), with options added to the dependency array. The component now sends requests continuously. Why, and how do you stop it?
Show answer
The object literal { method: 'GET' } is a new object on every render, so options changes identity each time and the effect re-runs. Each run calls setState, which re-renders the component, which creates a new object, and so on. Stop it by passing primitive values (for example a method string) as separate parameters, by defining the options object outside the component so it is created once, or by memoizing it with useMemo.