Fix Stale State & Race Conditions in React Data Fetching
Why fast clicks let slow API responses overwrite newer UI state, and how AbortController cancels stale requests cleanly.
By the end of this tutorial you will know:
- How out-of-order network responses overwrite newer search results
- How to cancel in-flight
fetch()calls usingAbortController - Why ignoring
AbortErroravoids false error banners
Prerequisites: Basic familiarity with React useEffect and fetch().
1. The big idea
Imagine a user types "go" in a search box, pauses 10ms, and changes it to "python". Request 1 ("go") happens to take 800ms on the server, while Request 2 ("python") returns in 150ms.
Request 2 updates the UI to "python" results—and then 650ms later, Request 1 finally arrives and overwrites the screen with "go" results!
2. Reproducing the race condition
useEffect(() => {
fetch(`/api/search?q=${encodeURIComponent(query)}`)
.then((r) => r.json())
.then((data) => setResults(data)); // stale response can win!
}, [query]);3. The fix: cancel stale requests with AbortController
Create an AbortController inside useEffect, pass its signal to fetch(), and call controller.abort() in the cleanup function.
"use client";
import { useEffect, useState } from "react";
export function SafeSearch({ query }: { query: string }) {
const [results, setResults] = useState<string[]>([]);
useEffect(() => {
const controller = new AbortController();
async function load() {
try {
const res = await fetch(`/api/search?q=${encodeURIComponent(query)}`, {
signal: controller.signal,
});
const data = (await res.json()) as string[];
setResults(data);
} catch (err) {
if (err instanceof DOMException && err.name === "AbortError") {
return; // Expected when a newer query supersedes this one
}
console.error(err);
}
}
void load();
return () => controller.abort();
}, [query]);
return <ul>{results.map((r) => <li key={r}>{r}</li>)}</ul>;
}Type rapidly in your search input with Network throttling enabled in DevTools. Earlier fetch requests show (canceled) in the Network tab, and only the latest query updates the UI.
4. Common pitfalls
| Mistake | Symptom | Fix |
|---|---|---|
Treating AbortError as a real failure | Flash of "Something went wrong" on fast typing | Check err.name === "AbortError" and return early |
Sharing one AbortController outside useEffect | All future requests stay aborted | Create a fresh new AbortController() inside each effect run |
5. What you learned
You now know how out-of-order responses cause stale UI bugs and how AbortController cancels superseded requests on cleanup.