React Development
Your React Search Shows the Wrong Results? Fix API Race Conditions Before They Ruin Your UI
Have you ever typed quickly into a React search box and seen older results replace newer ones? This can happen when API requests finish in a different order than they were sent. Learn how to prevent stale responses using AbortController, cleanup functions, and request-state management.
React Development
Your React Search Shows the Wrong Results? Fix API Race Conditions Before They Ruin Your UISearch results can become unpredictable when users type quickly and API requests finish in a different order than they started. Learn why this happens and how to prevent stale responses from replacing the latest results.
The problem: requests do not always finish in order
Imagine a user types "react" into your search box. Your application sends a request for every input change:
rrereareacreact
You might expect the requests to complete in the same order. Networks do not guarantee that.
The request for rea could finish after the request for react.
If every response updates the same state, older results can overwrite newer ones.
This is a race condition: the final UI depends on the timing of asynchronous operations rather than only on the latest user input.
1. A common implementation that causes the issue
This component sends a request whenever the search term changes:
import { useEffect, useState } from 'react';
function Search() {
const [query, setQuery] = useState('');
const [results, setResults] = useState([]);
useEffect(() => {
if (!query) {
setResults([]);
return;
}
fetch(`/api/search?q=${encodeURIComponent(query)}`)
.then(response => response.json())
.then(data => setResults(data));
}, [query]);
return (
<div>
<input
value={query}
onChange={event => setQuery(event.target.value)}
placeholder="Search..."
/>
{results.map(item => (
<p key={item.id}>{item.name}</p>
))}
</div>
);
}
The problem is not that fetch() is inherently unreliable. The problem is that this component accepts
every response, including a response for an older query.
2. Fix stale responses with AbortController
The browser's AbortController API lets you cancel a fetch request when the effect is cleaned up.
This is a good fit for search requests where newer input makes older results irrelevant.
import { useEffect, useState } from 'react';
function Search() {
const [query, setQuery] = useState('');
const [results, setResults] = useState([]);
const [loading, setLoading] = useState(false);
const [error, setError] = useState('');
useEffect(() => {
if (!query.trim()) {
setResults([]);
setLoading(false);
setError('');
return;
}
const controller = new AbortController();
async function search() {
setLoading(true);
setError('');
try {
const response = await fetch(
`/api/search?q=${encodeURIComponent(query)}`,
{ signal: controller.signal }
);
if (!response.ok) {
throw new Error('Search request failed');
}
const data = await response.json();
setResults(data);
} catch (err) {
if (err.name !== 'AbortError') {
setError(err.message || 'Something went wrong');
}
} finally {
if (!controller.signal.aborted) {
setLoading(false);
}
}
}
search();
return () => controller.abort();
}, [query]);
return (
<div>
<input
value={query}
onChange={event => setQuery(event.target.value)}
placeholder="Search..."
/>
{loading && <p>Searching...</p>}
{error && <p role="alert">{error}</p>}
{results.map(item => (
<p key={item.id}>{item.name}</p>
))}
</div>
);
}
When the query changes, React runs the previous effect's cleanup and aborts its fetch. The
AbortError is handled separately so a normal cancellation is not shown as an application error.
Important: aborting a browser request does not guarantee that the server never received or processed it. It prevents the obsolete client-side request from being treated as a successful current result.
3. Use an ignore flag when cancellation is not enough
Some asynchronous work cannot be cancelled. In those cases, you can prevent an outdated effect from updating state after cleanup by using a local flag.
useEffect(() => {
let ignore = false;
async function loadResults() {
const response = await fetch(
`/api/search?q=${encodeURIComponent(query)}`
);
const data = await response.json();
if (!ignore) {
setResults(data);
}
}
loadResults();
return () => {
ignore = true;
};
}, [query]);
The cleanup marks the previous effect as outdated. Its eventual response is ignored instead of replacing the latest state. In production code, also handle HTTP errors and rejected promises.
4. Reduce unnecessary requests with debouncing
Cancelling outdated requests helps correctness, but a search field can still send too many requests. Debouncing waits until the user pauses typing before starting the search.
useEffect(() => {
const timeoutId = setTimeout(() => {
setDebouncedQuery(query);
}, 300);
return () => clearTimeout(timeoutId);
}, [query]);
Use debouncedQuery as the search effect's dependency instead of the raw input.
A delay around 250â400 milliseconds is a common starting point; choose a value that fits your interface.
5. Build a better search experience
A reliable search interface should account for more than successful API responses:
- Show a loading indicator while the current search is running.
- Clear or retain old results intentionally when a new search starts.
- Display a useful error when the request fails.
- Show an empty state when a successful search returns no results.
- Ignore or cancel outdated requests.
- Encode user input before putting it into a URL.
- Handle empty and whitespace-only search terms.
6. Consider TanStack Query or SWR
For applications with many API calls, a data-fetching library can handle caching, request state, retries, and stale data more consistently than writing every request manually.
TanStack Query and SWR are popular choices in React applications. They do not remove the need to understand request lifecycles, but they provide reusable patterns for common data-fetching problems.
Final thoughts
A search box can look simple while hiding a complicated asynchronous workflow. When requests finish out of order, an older response can replace the results the user actually asked for.
Use effect cleanup, AbortController, or an ignore flag to stop stale responses from updating the UI.
Add debouncing to reduce unnecessary requests and make loading, error, and empty states clear.
The latest user input should control the resultsânot whichever network request happens to finish last.