Sub topic 5
Race conditions when inputs change
This chapter assumes you can write a component that fetches inside useEffect, tracks loading and error state, and checks response.ok. It also assumes you know that the dependency array controls when an effect re-runs. Here you will see how a fetch that is correct for one input can still show wrong data when the input changes quickly.
What a race condition is here
A race condition happens when the result of a program depends on the order in which things finish, and that order is not under your control. In a fetching component, the things racing are network requests.
Suppose UserProfile receives a userId prop. When the prop changes from 1 to 2, the effect runs again and starts a second request. The first request is still in flight. React does not cancel it. Both promises will eventually resolve, and each will call setUser.
Requests are not guaranteed to finish in the order they started. A server may answer user 2 from a cache in 40 ms and take 900 ms to answer user 1. The sequence then looks like this:
The final screen shows user 1 while the userId prop says 2. Nothing throws an error, and no warning appears. The interface is just wrong.
Reproducing the bug
The following component has the bug. It fetches in an effect and has no cleanup.
import { useEffect, useState } from 'react';
function UserProfile({ userId }) {
const [user, setUser] = useState(null);
useEffect(() => {
fetch(`/api/users/${userId}`)
.then((response) => {
if (!response.ok) {
throw new Error(`Request failed with status ${response.status}`);
}
return response.json();
})
.then((data) => setUser(data))
.catch((err) => console.error(err));
}, [userId]);
if (!user) return <p>Loading...</p>;
return <h1>{user.name}</h1>;
}On a fast local server you may never see the problem, because responses arrive in order. It shows up with real conditions: slow networks, uneven server load, and a user who clicks through a list quickly. To reproduce it on purpose, open the browser's developer tools, throttle the network, and switch between ids several times. Another option is to add an artificial delay to one id on a test server.
Why the order is not guaranteed
Several things can reorder responses:
- Servers take different amounts of time for different records.
- A response may come from a CDN or HTTP cache for one URL and from the origin for another.
- Requests can travel on different connections, and one may be retried after packet loss.
- A request that hits a cold start in a serverless backend takes far longer than one that hits a warm instance.
You cannot fix this by making the server faster. You have to make the client ignore answers it no longer needs.
The same bug appears outside of ids
The userId example is the clearest, but the problem appears wherever an effect depends on a value that can change while a request is in flight:
- Search boxes. Typing "re", then "rea", then "reac" sends three requests. If the response for "re" arrives last, the results list shows matches for the wrong text.
- Pagination and tabs. Clicking page 2 and then page 3 quickly can leave page 2 on screen under a "page 3" label.
- Filters and sort order. Any control that feeds a query parameter can trigger it.
In each case the stale response is valid data. It simply belongs to an input the user has already moved past.
Fixing it with an ignore flag
The smallest fix uses the cleanup function. React calls the function returned from an effect before it runs the effect again with new values, and again when the component unmounts. Each effect run gets its own closure, so a variable declared inside the effect belongs to that run alone.
import { useEffect, useState } from 'react';
function UserProfile({ userId }) {
const [user, setUser] = useState(null);
useEffect(() => {
let ignore = false;
fetch(`/api/users/${userId}`)
.then((response) => {
if (!response.ok) {
throw new Error(`Request failed with status ${response.status}`);
}
return response.json();
})
.then((data) => {
if (!ignore) setUser(data);
})
.catch((err) => {
if (!ignore) console.error(err);
});
return () => {
ignore = true;
};
}, [userId]);
if (!user) return <p>Loading...</p>;
return <h1>{user.name}</h1>;
}Trace what happens when userId goes from 1 to 2:
- The first effect run starts the request for user 1 with its own
ignoreset tofalse. - The prop changes. React runs the cleanup from the first run, which sets that run's
ignoretotrue. - React runs the effect again. The second run has a new
ignore, stillfalse, and requests user 2. - If the user 1 response arrives, its callback sees
ignore === trueand does nothing. - The user 2 response sets the state.
The order of the responses no longer matters, because only the latest effect run is allowed to write state.
What the flag does not do
The ignore flag fixes the display, but the old request still runs to completion. The browser downloads the full body, and the server does all the work. For a small JSON response this is harmless. For large payloads or expensive queries it wastes bandwidth and server capacity.
The next chapter replaces the flag with AbortController, which tells the browser to cancel the request itself. The flag remains a useful tool for work that cannot be cancelled, such as a call into a library that returns a promise but accepts no signal.
Stale loading and error state
The ignore flag guards every state update, not only the data. A common mistake is to guard setUser but leave the other setters unguarded. Consider a component that also tracks loading and error state:
import { useEffect, useState } from 'react';
function UserProfile({ userId }) {
const [user, setUser] = useState(null);
const [error, setError] = useState(null);
const [isLoading, setIsLoading] = useState(true);
useEffect(() => {
let ignore = false;
setIsLoading(true);
setError(null);
fetch(`/api/users/${userId}`)
.then((response) => {
if (!response.ok) {
throw new Error(`Request failed with status ${response.status}`);
}
return response.json();
})
.then((data) => {
if (ignore) return;
setUser(data);
setIsLoading(false);
})
.catch((err) => {
if (ignore) return;
setError(err);
setIsLoading(false);
});
return () => {
ignore = true;
};
}, [userId]);
if (isLoading) return <p>Loading...</p>;
if (error) return <p>Error: {error.message}</p>;
return <h1>{user.name}</h1>;
}If the catch branch were unguarded, a failed request for user 1 could show an error message for user 2 after user 2 had loaded successfully. If setIsLoading(false) were unguarded, a late response for user 1 could remove the loading indicator while user 2 was still loading, and user.name would then read stale or null data.
Edge cases to check
- Stale data during loading. When
userIdchanges,userstill holds the previous person until the new response arrives. TheisLoadingcheck hides it here. If you remove that check, the old name stays on screen under the new id. - Unmount. The cleanup also runs on unmount, so the flag stops updates to a component that is no longer on screen.
- Rapid changes. With three quick changes (1, 2, 3), the cleanup sets the flag on runs 1 and 2. Only run 3 can write state, whichever response arrives first.
- Same value. If a re-render keeps
userIdthe same, the dependency array is unchanged and the effect does not re-run, so no new request starts and the existing request is not ignored.
A way to test it
You can confirm the fix without a real server by faking fetch with controlled delays. This test uses Vitest and React Testing Library, and assumes the component above is exported from UserProfile.jsx.
import { render, screen } from '@testing-library/react';
import { expect, it, vi } from 'vitest';
import UserProfile from './UserProfile';
function delayedResponse(name, ms) {
return new Promise((resolve) => {
setTimeout(() => resolve({ ok: true, json: async () => ({ name }) }), ms);
});
}
it('shows the latest user even when an older response arrives last', async () => {
globalThis.fetch = vi.fn((url) =>
url.endsWith('/1') ? delayedResponse('Ada', 200) : delayedResponse('Grace', 20)
);
const { rerender } = render(<UserProfile userId={1} />);
rerender(<UserProfile userId={2} />);
expect(await screen.findByText('Grace')).toBeTruthy();
await new Promise((resolve) => setTimeout(resolve, 300));
expect(screen.queryByText('Ada')).toBeNull();
});The test fails against the version without the flag, because "Ada" replaces "Grace" after 200 ms. It passes with the flag.
Summary of the failure and the guard
| Situation | Without a guard | With cleanup |
|---|---|---|
| Responses arrive in order | Correct | Correct |
| Older response arrives last | Stale data shown | Older response ignored |
| Component unmounts mid-request | Update after unmount | Update skipped |
| Request fails for an old input | Wrong error shown | Error ignored |
Exercise
A search component runs fetch(/api/search?q=${query}) in an effect that depends on [query]. The user types "ab" and then "abc". The response for "abc" arrives first, followed by the response for "ab". There is no cleanup function. What does the results list show at the end, and which change fixes it?
Show answer
The list shows results for "ab", while the input shows "abc", because the late "ab" response calls the state setter last. Declare let ignore = false inside the effect, check if (!ignore) before every state update in the then and catch handlers, and return a cleanup function that sets ignore = true. The cleanup for the "ab" run executes when query changes to "abc", so its late response is discarded.
Exercise
Why must the ignore variable be declared inside the effect and not in the component body with useRef?
Show answer
Each effect run needs its own flag so that cleanup can mark only that run as outdated. A ref is shared across all runs. Cleanup of run 1 would set the shared flag to true, and run 2 would then have to reset it, which lets run 1's late response pass the check again once run 2 starts. A variable inside the effect avoids this because each run closes over a separate copy.