Sub topic 2
Race Conditions When Inputs Change
Assume you know JavaScript promises, React props, JSX, and useState. A race condition happens when asynchronous operations finish in an unexpected order.
Stale responses
Suppose a profile component fetches user 1, then quickly receives userId="2". The second request might finish first. If the first request finishes later and updates state, the screen shows user 1 even though the current prop is user 2.
The effect must cancel or ignore work from its previous run.
Cleaning up with AbortController
AbortController is a browser API that cancels an operation that accepts its signal. The effect creates one controller for each request and aborts it during cleanup.
import { useEffect, useState } from 'react';
function UserProfile({ userId }) {
const [state, setState] = useState({
status: 'loading',
data: null,
error: null,
});
useEffect(() => {
const controller = new AbortController();
setState({ status: 'loading', data: null, error: null });
fetch(`/api/users/${userId}`, { signal: controller.signal })
.then((response) => {
if (!response.ok) {
throw new Error(`Request failed: ${response.status}`);
}
return response.json();
})
.then((data) => setState({ status: 'success', data, error: null }))
.catch((error) => {
if (error.name === 'AbortError') return;
setState({ status: 'error', data: null, error });
});
return () => controller.abort();
}, [userId]);
if (state.status === 'loading') return <p>Loading...</p>;
if (state.status === 'error') return <p>{state.error.message}</p>;
return <h1>{state.data.name}</h1>;
}The dependency array makes the effect run when userId changes. Cleanup runs before the next effect, so the old request cannot update state after cancellation.
Why effects run twice in development
React Strict Mode runs an effect, its cleanup, and the effect again during development. This exposes missing cleanup and non-idempotent side effects. The first request is aborted in the example, so only the second request can update state. Production does not use this extra development check.
Extracting a useFetch hook
A custom hook packages this state machine for reuse.
export function useFetch(url) {
const [state, setState] = useState({
status: 'loading',
data: null,
error: null,
});
useEffect(() => {
const controller = new AbortController();
setState({ status: 'loading', data: null, error: null });
fetch(url, { signal: controller.signal })
.then((response) => {
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return response.json();
})
.then((data) => setState({ status: 'success', data, error: null }))
.catch((error) => {
if (error.name !== 'AbortError') {
setState({ status: 'error', data: null, error });
}
});
return () => controller.abort();
}, [url]);
return state;
}Avoiding request waterfalls
A request waterfall occurs when request B starts only after request A finishes. Fetch independent data in the same parent effect, or use a data library that coordinates requests.
Exercise
Why does the effect depend on userId, and what does its cleanup do?
Show answer
userId starts a new request when the requested user changes. Cleanup aborts the previous request so a stale response cannot update state.