Skip to content

Only the Current Request May Win

The Course
•
18 min study

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:

JSX
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.

Only the Current Request May Win Next.js · 5 files
import "./globals.css"; export default function RootLayout({ children }) { return ( <html lang="en"> <body> <header> <strong>Study Library · Practice lab</strong> </header> {children} </body> </html> ); } import SearchBox from "./SearchBox.jsx"; export default function Page() { return ( <main> <h1>Only the Current Request May Win</h1> <SearchBox /> </main> ); } "use client"; import { useEffect, useState } from "react"; export default function SearchBox() { const [query, setQuery] = useState(""); const [answer, setAnswer] = useState(null); 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]); return ( <section> <label> Search <input value={query} onChange={(event) => setQuery(event.target.value)} /> </label> {answer && ( <> <p role="status">Results for “{answer.q}”</p> <ul> {answer.matches.map((title) => ( <li key={title}>{title}</li> ))} </ul> </> )} </section> ); } body { font: 16px/1.5 system-ui; margin: 0; color: #182b3c; background: #f4f8fc; } header, main { max-width: 900px; margin: auto; padding: 20px; } header { border-bottom: 1px solid #cbd5e1; } a { color: #075985; } button, input, textarea, select { font: inherit; padding: 8px; margin: 4px; } button { cursor: pointer; } table { border-collapse: collapse; width: 100%; } th, td { padding: 10px; border: 1px solid #cbd5e1; text-align: left; vertical-align: top; } pre, code { white-space: pre-wrap; overflow-wrap: anywhere; } .pass { color: #166534; } .fail, [role="alert"] { color: #a01818; } section { margin: 16px 0; padding: 12px; background: white; border-radius: 8px; } nav { display: flex; gap: 16px; } const titles = ["React basics", "React forms", "Reading data", "Routing", "Server actions"]; export async function GET(request) { const q = new URL(request.url).searchParams.get("q") ?? ""; // Short queries match more rows, so this pretend search is slower for them. await new Promise((resolve) => setTimeout(resolve, q.length <= 2 ? 900 : 200)); const matches = titles.filter((title) => title.toLowerCase().includes(q.toLowerCase())); return Response.json({ q, matches }); }
Runs with real Next.js on your computer: unzip, then npm install and npm run dev.
Add and remove files here; write their code in the editor.
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:

Text
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 wins

Each .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:

JSX
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.

Exercise

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.

Your working space Next.js · 5 files
import "./globals.css"; export default function RootLayout({ children }) { return ( <html lang="en"> <body> <header> <strong>Study Library · Practice lab</strong> </header> {children} </body> </html> ); } import SearchBox from "./SearchBox.jsx"; export default function Page() { return ( <main> <h1>Only the Current Request May Win</h1> <SearchBox /> </main> ); } "use client"; import { useEffect, useState } from "react"; export default function SearchBox() { const [query, setQuery] = useState(""); const [answer, setAnswer] = useState(null); 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]); return ( <section> <label> Search <input value={query} onChange={(event) => setQuery(event.target.value)} /> </label> {answer && ( <> <p role="status">Results for “{answer.q}”</p> <ul> {answer.matches.map((title) => ( <li key={title}>{title}</li> ))} </ul> </> )} </section> ); } body { font: 16px/1.5 system-ui; margin: 0; color: #182b3c; background: #f4f8fc; } header, main { max-width: 900px; margin: auto; padding: 20px; } header { border-bottom: 1px solid #cbd5e1; } a { color: #075985; } button, input, textarea, select { font: inherit; padding: 8px; margin: 4px; } button { cursor: pointer; } table { border-collapse: collapse; width: 100%; } th, td { padding: 10px; border: 1px solid #cbd5e1; text-align: left; vertical-align: top; } pre, code { white-space: pre-wrap; overflow-wrap: anywhere; } .pass { color: #166534; } .fail, [role="alert"] { color: #a01818; } section { margin: 16px 0; padding: 12px; background: white; border-radius: 8px; } nav { display: flex; gap: 16px; } const titles = ["React basics", "React forms", "Reading data", "Routing", "Server actions"]; export async function GET(request) { const q = new URL(request.url).searchParams.get("q") ?? ""; // Short queries match more rows, so this pretend search is slower for them. await new Promise((resolve) => setTimeout(resolve, q.length <= 2 ? 900 : 200)); const matches = titles.filter((title) => title.toLowerCase().includes(q.toLowerCase())); return Response.json({ q, matches }); }
Runs with real Next.js on your computer: unzip, then npm install and npm run dev.
Add and remove files here; write their code in the editor.
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
JSX
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.

Was this article helpful?

Your response is saved on this device.