Sub topic 5
Race conditions when inputs change
This chapter assumes you can write a useEffect that fetches data, keep loading, error, and success state in useState, and read promise chains. It covers what goes wrong when the effect's inputs change while a request is still running.
How the race happens
An effect that depends on userId runs again each time userId changes. The earlier request is not canceled. It keeps running, and its .then callback still runs when the response arrives.
Network responses do not arrive in the order the requests were sent. Suppose the user clicks profile 1, then quickly clicks profile 2:
- The effect sends request A for user 1.
userIdchanges, and the effect sends request B for user 2.- Request B finishes first and the screen shows user 2.
- Request A finishes late and overwrites the state with user 1.
The component now shows user 1 while userId is 2. No error is thrown, so the bug is easy to miss in development, where the server is fast and local.
A code version that has the bug
import { useEffect, useState } from 'react';
function UserName({ userId }) {
const [name, setName] = useState('');
useEffect(() => {
fetch(`/api/users/${userId}`)
.then((response) => response.json())
.then((data) => setName(data.name));
}, [userId]);
return <h1>{name}</h1>;
}Nothing in this effect checks whether the response still belongs to the current userId.
Fix: ignore stale responses
An effect can return a cleanup function. React runs it before the next run of the effect and when the component unmounts. Use it to mark the current run as outdated:
import { useEffect, useState } from 'react';
function UserName({ userId }) {
const [name, setName] = useState('');
useEffect(() => {
let ignore = false;
fetch(`/api/users/${userId}`)
.then((response) => response.json())
.then((data) => {
if (!ignore) {
setName(data.name);
}
});
return () => {
ignore = true;
};
}, [userId]);
return <h1>{name}</h1>;
}Each run of the effect has its own ignore variable, because each run creates a new closure. When userId changes, cleanup sets the old run's ignore to true. If response A arrives late, its callback sees ignore is true and skips setName.
This fixes the visible bug. The old request still goes over the network and still consumes bandwidth. The next chapter shows how AbortController cancels it.
Common mistakes
- Checking the wrong value. Comparing against a state variable inside the callback reads the value captured when the effect ran, not the latest one. The
ignoreflag set by cleanup is the reliable signal. - Leaving out a dependency. If the effect uses
userIdbut the array is[], the effect never re-runs, so there is no race but the data is simply wrong. - Resetting loading state only on the first run. When the input changes, set loading to
trueagain, or the old user's data stays on screen as if it were current.
Exercise
A component fetches /api/search?q=${query} in an effect with [query] as its dependencies. The user types "re" and then "react". The response for "react" arrives first, then the response for "re". Which results are on screen at the end, and which one-line change in the effect's cleanup prevents this?
Show answer
The results for "re" are on screen, because its late response overwrites the newer one. Declare let ignore = false; in the effect, check if (!ignore) before setting state, and return a cleanup function that sets ignore = true.