Fixing a Type-Ahead Search Box That Shows Stale Results
System DesignModel answerLast updated
Diagnose why a React search component sometimes displays results for an older query, then fix it with effect cleanup and request cancellation, and prove the fix with a deterministic test.
You own a small search box built in React. Each time the text in the input changes, the component calls a search endpoint and renders the returned list. Support tickets say the list on screen sometimes belongs to something the user typed a moment earlier, not to the text currently in the box. When you test the endpoint directly, every response is correct for the query that was sent, so the server is not at fault.
import { useEffect, useState } from "react";
type Result = { id: string; name: string };
export function SearchResults() {
const [query, setQuery] = useState("");
const [results, setResults] = useState<Result[]>([]);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
if (!query) {
setResults([]);
return;
}
fetch(`/api/search?q=${encodeURIComponent(query)}`)
.then(res => res.json())
.then(data => setResults(data.results))
.catch(() => setError("Search failed"));
}, [query]);
return (
<div>
<input value={query} onChange={e => setQuery(e.target.value)} />
{error && <p>{error}</p>}
<ul>
{results.map(r => (
<li key={r.id}>{r.name}</li>
))}
</ul>
</div>
);
}
Requirements
- The endpoint is correct per request; the defect is on the client.
- Once typing stops, the screen must show the results for the final input. It must never switch to results for an earlier input. Leaving the old list visible while a new request is in flight is fine.
- Use standard browser APIs and avoid adding unnecessary network traffic.
What to produce
- Describe how you would reproduce the problem reliably.
- Explain the root cause in terms of this component's code.
- Provide a corrected version, including how it treats errors caused by the fix itself.
- Point out any other defects in the snippet that affect what the user sees.
- Describe how you would verify the fix with an automated, deterministic test.
You may also discuss questions such as whether the backend could echo the query it answered, whether debouncing is acceptable, and whether the user should ever see an error for a request that is no longer needed.
Hints
Hint 1
Network responses do not have to arrive in the order the requests were sent. Ask what happens to the state when the response for an older query arrives after the response for a newer one.
Hint 2
An effect can return a cleanup function that runs before the next effect and on unmount. Think about what that cleanup could do to the request that is still in flight, and what kind of error cancelling produces.
Hint 3
Look beyond the race: what happens to a stale error message, to non-2xx responses, and to the empty-query branch that returns while a request is still pending?
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Reproduce first
Do not guess. Make the race visible before touching the code.
- In browser DevTools, throttle the network and type "re", then "react" quickly. Or use request blocking/overrides to delay only the first request.
- Better, in a test, mock
fetchso that the request for the first query resolves after the request for the second one. This forces the failure every time instead of occasionally. - Symptom: the input shows
react, but the list shows results forre.
Root cause
The effect starts a request for each value of query, but nothing ties a response to the query that is current when it lands. Each .then(... setResults ...) callback is a closure that writes to state whenever its response arrives.
Sequence:
- The user types
re. Request A starts. - The user types
react. Request B starts. - B returns first (it may be faster, cached, or served by a different server).
resultsis set to thereactlist. - A returns late. Its callback still runs and overwrites
resultswith therelist.
The final screen shows results for an older input. The server is correct in each case. The bug is that the client treats "last response to arrive" as "response to the latest query". Response order is not guaranteed to equal request order.
The fix: cancel in the effect cleanup
Each effect run owns one request. When the effect re-runs (query changed) or the component unmounts, the cleanup aborts the old request, so it can never write to state.
useEffect(() => {
if (!query) {
setResults([]);
setError(null);
return;
}
const controller = new AbortController();
setError(null);
(async () => {
try {
const res = await fetch(
`/api/search?q=${encodeURIComponent(query)}`,
{ signal: controller.signal }
);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const data = await res.json();
if (!controller.signal.aborted) setResults(data.results);
} catch (e) {
if ((e as Error).name === "AbortError") return; // expected, ignore
if (!controller.signal.aborted) setError("Search failed");
}
})();
return () => controller.abort();
}, [query]);
Why this is correct:
- Cleanup runs before the next effect for a new
query, so at most one request is "live" at any time, and it is always the one for the current query. AbortControlleralso frees the connection and stops downloading data nobody needs, so it reduces traffic rather than adding any.- The extra
signal.abortedcheck guards the gap where the response has already arrived but the body is still being parsed when the abort happens.
Errors introduced by the fix
Aborting makes fetch reject with a DOMException named AbortError. In the original .catch, that would show "Search failed" every time the user types another character. The fix must treat AbortError as expected and silent. The answer to "should the user see an error for a request that is no longer needed?" is no.
Other defects in the snippet
- Non-2xx responses.
fetchonly rejects on network failure. A 500 with a JSON body would flow intodata.results, possibly settingundefinedand crashing.map. Checkres.ok. - Stale error never clears. Once
erroris set, it stays even after later successful searches. Reset it when a new search starts. - Empty query path. With the original code, clearing the input does not cancel an in-flight request, so a late response can repopulate the list after it was cleared. With cleanup, the pending request is aborted when
querychanges to empty. - Loading state. There is no indicator, so users cannot tell whether the list is current. Optional, but worth a mention.
- Defensive shape check.
data.results ?? []avoids a crash on unexpected payloads.
Alternatives and trade-offs
| Option | Pros | Cons |
|---|---|---|
AbortController in cleanup (chosen) | Standard API, cancels network work, simple | Need to handle AbortError |
ignore flag in cleanup (let ignore = false; return () => { ignore = true }) | Works with any async source, even non-abortable ones | Request still completes, wasting bandwidth |
| Debounce (about 250 to 300 ms) | Far fewer requests | Adds latency, and does not remove the race by itself, since slow responses can still reorder. Use it together with cancellation |
| Server echoes the query, client compares to current input | Robust against any ordering | Requires a backend change; still wastes requests |
| A data library (React Query, SWR) | Handles keys, cancellation, caching | New dependency; hides the mechanism |
Debouncing is a good addition for traffic, but cancellation is what guarantees correctness.
Deterministic test
Avoid real timers and real network. Control resolution order by hand.
- Mock
fetchso each call returns a promise whoseresolveyou capture, and honor thesignal(reject with anAbortErrorwhen it aborts). - Render the component, type
re, then typereact. - Resolve the
reactrequest with[{ id: "2", name: "React" }]. - Resolve the
rerequest with[{ id: "1", name: "Redux" }]. If the mock honors abort, this one has already been rejected; if you test theignore-style guard, resolve it anyway. - Assert the list shows
Reactand does not containRedux, and that no "Search failed" text appears.
Add further cases: a 500 response shows the error; the error clears on the next successful search; clearing the input empties the list even if a response is still pending; unmounting mid-request triggers no state update warning.
Before the fix, step 4 overwrites the list and the test fails every time, which proves the test actually catches the bug.
Common mistakes
- Blaming the backend because individual calls look fine.
- Adding a debounce and calling it fixed.
- Aborting but leaving
.catchto show an error onAbortError. - Using a shared mutable variable outside the effect rather than per-effect state, which breaks under React strict mode's double invocation of effects. Per-run controllers handle this correctly.