The decision
A search box that fetches as the reader types sends one request per change. Requests leave in the order the reader typed, but they finish in whatever order the server answers. If an older, slower answer arrives last, it replaces the newer one, and the screen shows results for something the reader is no longer searching for.
Read, predict, run
SearchBox.jsx is a Client Component. Its effect runs whenever query
changes, fetches /api/search, and stores the answer:
useEffect(() => {
if (!query) return;
fetch(`/api/search?q=${encodeURIComponent(query)}`)
.then((response) => response.json())
.then((data) => {
console.log(`answer for "${data.q}" arrived`);
setAnswer(data);
});
}, [query]);The route handler app/api/search/route.js is slow for short queries
(900 ms for two letters or fewer) and quick for longer ones (200 ms), the way a
broad search can be.
Run the lab, type re, then quickly finish the word to react. Before you do, predict which Results for … line the box ends on.
npm install and npm run dev. Check your prediction
Results for “re”, though the box says react. The console shows the order: answer for "react" arrived, then answer for "re" arrived. Trace it:
0 ms query "re": request A leaves (900 ms)
100 ms query "react": request B leaves (200 ms)
300 ms B arrives: setAnswer(react results)
900 ms A arrives: setAnswer(re results) <- the stale answer winsEach .then was written when its request left, and nothing told request A's
callback that the query had moved on.
Cleanup marks an answer as stale
An effect can return a cleanup function. React runs it before the effect runs again with new values, and when the component unmounts. That's exactly the moment a request becomes obsolete. So each run of the effect gets its own flag, and its cleanup sets it:
useEffect(() => {
let ignore = false;
// …start the request; when it answers:
// if (ignore) return;
return () => {
ignore = true;
};
}, [query]);Each run of the effect has its own ignore variable, captured by its own
callbacks. When the query changes to react, React calls the re run's
cleanup, which sets the re run's ignore to true. The react run's
flag stays false.
The failure to avoid
Don't compare data.q === query inside the callback: that query is the one
captured when the request left, so it always matches its own answer. The flag
per run is the simplest correct pattern.
The flag doesn't cancel the request: the server still does the work, and the
answer still downloads. AbortController can actually cancel a fetch; pass
its signal to fetch and call abort() in the cleanup. Either way, the old
answer must not reach state.
Ignore the obsolete answer
Change the effect in SearchBox.jsx so typing re then react quickly
ends on Results for “react”, with React basics and React forms. The
console should log only the answer that was kept.
npm install and npm run dev. Hint 1: the idea
The effect for re needs to learn, later, that it has been replaced. The cleanup function is how React tells it, and a variable that only that run's callbacks can see is where the news is kept.
Hint 2: a first step
Declare let ignore = false; at the top of the effect and return a cleanup
that sets it to true. Run the experiment again: nothing changes yet. Where
must the effect read the flag?
Show one solution
useEffect(() => {
if (!query) return;
let ignore = false;
fetch(`/api/search?q=${encodeURIComponent(query)}`)
.then((response) => response.json())
.then((data) => {
if (ignore) return;
console.log(`answer for "${data.q}" arrived`);
setAnswer(data);
});
return () => {
ignore = true;
};
}, [query]);The check sits in the last callback, just before setAnswer, because that's
the moment an old answer could do harm. When react replaced re, React
ran the re effect's cleanup, so request A's callback finds its own ignore
set and returns. Checking the flag before fetch instead would do nothing:
at that point the query hasn't changed yet.
Explain it without the code
A reader picks a different tab while the first tab's data is still loading. Write which request each tab's effect starts, which cleanup runs, and which answer ends up on screen.
Going further
Fetching in an effect is fine for search-as-you-type. When the search lives in
the URL, as in the previous lesson, the server component can read searchParams and
React handles the ordering for you. See React's guide to
fetching data in effects.
Completion is saved in this browser only. It does not measure mastery.