Sub topic 7
Fetching data and avoiding race conditions
This chapter assumes you know function components, useState, closures, Promises, and the browser fetch API. You should also know how the dependency array and cleanup functions work from the previous chapters.
Why fetching belongs in an effect
Fetching data is a side effect. It talks to something outside React, and it must not happen while a component renders. Render must stay pure, so you start the request after the component commits to the screen. That is what useEffect is for.
The usual pattern has three parts:
- State that holds the result, plus state for loading and errors.
- An effect that starts the request when its inputs change.
- A cleanup function that stops the previous request from affecting the screen.
The third part is the one people skip. It is also the one that prevents most bugs.
The race condition
A race condition happens when the result depends on which of two asynchronous operations finishes first. Here is a naive version of a user profile component:
import { useEffect, useState } from 'react';
function User({ userId }) {
const [user, setUser] = useState(null);
useEffect(() => {
fetch(`/api/users/${userId}`)
.then((res) => res.json())
.then(setUser);
}, [userId]);
return user ? <h1>{user.name}</h1> : <p>Loading...</p>;
}Suppose userId changes from 1 to 2. React runs the effect twice, so two requests are in flight. Network responses do not arrive in a guaranteed order. If the request for user 2 finishes first and the request for user 1 finishes later, setUser is called with user 1's data last. The screen shows user 1 while userId is 2. The UI and the props disagree, and nothing in the code reports an error.
Fix 1: abort the previous request
The cleanup function runs before the effect re-runs, and when the component unmounts. You can use it to cancel the request that is no longer relevant. AbortController is the browser API for this.
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>;
}Here is what happens when userId changes from 1 to 2:
- React calls the cleanup from the previous effect, which aborts the request for user 1.
- The pending
fetchpromise for user 1 rejects with anAbortError. - The
catchhandler sees theAbortErrorand ignores it. Aborting is expected, so it is not a failure to show the user. - The new effect starts the request for user 2.
Because the old request is cancelled, it can no longer call setUser. Only the latest request can update state.
Check `res.ok`
fetch only rejects on network failures. A 404 or 500 response resolves normally. If you skip the res.ok check, you will try to parse an error page as data, or store an error body as if it were a user. The example above turns non-2xx responses into thrown errors so one catch handles both cases.
Fix 2: an ignore flag
Aborting needs an API that supports it. Sometimes you are using a library that returns a plain Promise with no cancellation. In that case, use a flag in the effect's closure that cleanup flips:
import { useEffect, useState } from 'react';
async function fetchUser(id) {
const res = await fetch(`/api/users/${id}`);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.json();
}
function User({ userId }) {
const [user, setUser] = useState(null);
const [error, setError] = useState(null);
useEffect(() => {
let ignore = false;
setUser(null);
setError(null);
async function load() {
try {
const data = await fetchUser(userId);
if (!ignore) setUser(data);
} catch (err) {
if (!ignore) setError(err);
}
}
load();
return () => {
ignore = true;
};
}, [userId]);
if (error) return <p>Failed to load: {error.message}</p>;
if (!user) return <p>Loading...</p>;
return <h1>{user.name}</h1>;
}Each run of the effect creates its own ignore variable. When userId changes, cleanup sets the old run's flag to true. The old response still arrives, but the check discards it. This is a closure doing useful work: every effect run remembers its own ignore.
Note that the callback passed to useEffect cannot itself be async. An async function returns a Promise, and React expects either nothing or a cleanup function. Define an async function inside the effect and call it, as load does above.
| Technique | Cancels the network request | Prevents stale state updates | Needs API support |
|---|---|---|---|
| `AbortController` | Yes | Yes | Yes, the call must accept a `signal` |
| `ignore` flag | No | Yes | No |
You can combine both. Abort to save bandwidth, and keep a flag if other code in the same chain might still call a setter.
Loading and error state
The examples reset user and error at the start of each effect run. Without that reset, the old user stays on screen while the new one loads, which can look like a correct page for the wrong ID. Resetting makes the loading state honest.
Three separate state variables can drift apart. If you want to avoid impossible combinations such as "loading and error at once", derive the status from the data you have, as the examples do. If error is set, show the error. Otherwise, if user is empty, show loading. Otherwise show the data.
For larger components, a single state object or useReducer with a status field ('loading', 'success', 'error') keeps the transitions in one place.
Edge cases
- Strict Mode in development. React mounts, unmounts, and mounts again to check your cleanup. You will see two requests for the first render. With
AbortController, the first is aborted and the second completes. This is correct behavior, not a bug. Do not add a "ran once" ref to hide it. - Unmounting mid-request. Cleanup runs on unmount, so both fixes stop updates to an unmounted component.
- Several dependencies. If the effect depends on
userIdandquery, a change to either one starts a new request and cancels the old one. - Request bodies and headers. Anything the effect reads from props or state must be in the dependency array, or the request may use outdated values.
- Non-idempotent requests. Effects are for reading. A
POSTthat creates an order should run in an event handler, because effects can run more than once.
When to stop writing this by hand
The code above handles one component. A real application also needs caching, retries, deduplicating identical requests, refetching when the window regains focus, and sharing results between components. Writing all of that in effects is error-prone. Libraries such as TanStack Query and SWR, and the data loading features of frameworks like Next.js and React Router, solve these problems. Use them in production code. Understanding the effect version still matters, because it explains what those tools do and why.
If you need the same fetching logic in several components, extract it into a custom hook. Later chapters cover that.
Summary
- Fetching is a side effect, so start it in an effect, not during render.
- Overlapping requests can resolve out of order, and the last response to arrive wins unless you prevent it.
- Cleanup is the tool for this. Use
AbortControllerwhen the API supports it, and anignoreflag when it doesn't. - Treat
AbortErroras expected, and checkres.okbecausefetchdoes not reject on HTTP errors. - Reset result and error state at the start of each run so the UI never shows data for the wrong input.
- For production apps, prefer a data-fetching library over hand-written effects.
Exercise
In the ignore flag version, a request for user 1 is still running when userId changes to 2, and both requests succeed. The response for user 2 arrives first, then the response for user 1. Which ignore values do the two effect runs have when their responses arrive, and what does the screen show at the end?
Show answer
The run for user 1 had its cleanup called when userId changed, so its ignore is true. The run for user 2 has ignore equal to false. The user 2 response calls setUser and the user 1 response is discarded by the if (!ignore) check. The screen ends up showing user 2.
Exercise
Why can you not write useEffect(async () => { ... }, [userId]), and what do you do instead?
Show answer
An async function always returns a Promise. React expects the effect callback to return either nothing or a cleanup function, so it would treat the Promise as the cleanup value and your real cleanup could never run. Define an async function inside the effect body and call it, returning the cleanup function from the effect itself.