Sub topic 7
Fetching data and avoiding race conditions
This chapter assumes you know function components, useState, closures, Promises, and fetch. You should also know how the dependency array and cleanup functions work from the earlier chapters.
Why fetching belongs in an effect
Fetching data is a side effect. It talks to something outside React, so it cannot run during rendering. An effect lets you start the request after the component renders and re-run it when an input such as userId changes.
A first version and its problem
A simple version fetches in an effect and stores the result in state:
useEffect(() => {
fetch(`/api/users/${userId}`)
.then((res) => res.json())
.then(setUser);
}, [userId]);This works until userId changes quickly. Say the user selects user 1, then user 2. Both requests are in flight. Responses can arrive in any order. If the response for user 1 arrives last, setUser stores user 1's data while the screen is supposed to show user 2. This is a race condition: the final state depends on network timing, not on the latest input.
Fixing it with cleanup and AbortController
The cleanup function runs before the effect re-runs and when the component unmounts. 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 how it behaves:
- The effect runs for
userId1 and starts request 1. userIdchanges to 2. React runs the cleanup first, which aborts request 1.- The effect runs again and starts request 2.
- The aborted request rejects with an
AbortError, which thecatchignores.
Only the latest request can update state.
Details that cause bugs
- Check
res.ok.fetchonly rejects on network failure. A 404 or 500 still resolves, so you must turn it into an error yourself. - Ignore
AbortError. Aborting is expected, not a failure. Showing it as an error would flash a message on every change. - Reset state at the start. Without
setUser(null), the old user stays on screen while the new one loads. - Don't make the effect callback
async. An async function returns a Promise, but React expects either nothing or a cleanup function. Put an async function inside the effect, or use.then.
Strict Mode and when to stop hand-writing this
In development, Strict Mode runs the effect, cleanup, and effect again. With the code above, the first request is aborted and the second one completes. This is correct behavior, and it confirms that your cleanup works. Production runs the effect once.
Writing this in every component is repetitive. Data-fetching libraries and framework loaders handle cancellation, caching, and retries for you. A custom hook can also wrap the pattern, which a later chapter covers.
Exercise
A component fetches /api/users/${userId} in an effect with [userId] as dependencies but has no cleanup. The user clicks through ids 1, 2, and 3 quickly. Why can the screen end up showing user 1, and what is the fix?
Show answer
Each id starts its own request, and responses can arrive out of order. If user 1's response arrives last, setUser overwrites the newer data. Fix it by creating an AbortController in the effect, passing its signal to fetch, and calling controller.abort() in the cleanup. Ignore errors whose name is AbortError.