Why an Old Search Response in React Overwrites a New One and How useEffect Cleanup Fixes ItBrief · digest for November 25
Brief≈ 2 min

Why an Old Search Response in React Overwrites a New One and How useEffect Cleanup Fixes It

You type "React" into a search box, and a split second later add "React hooks". Two requests fly out. The second often finishes first and renders the fresh list, then the first arrives late and overwrites the screen with stale results. Networks never guarantee response order.

To discard the late response, the React useEffect docs recommend an ignore flag inside the cleanup function:

useEffect(() => {
  // Track whether this effect run is still current
  let ignore = false;

  async function load() {
    const data = await fetchResults(query);
    if (!ignore) setResults(data);
  }

  load();
  // On a new query, React cleans up the old effect first
  return () => {
    ignore = true;
  };
}, [query]);

When query changes or the component unmounts, React runs the previous cleanup first: ignore becomes true, and the late response is ignored. This also prevents duplicate runs in StrictMode from causing trouble.

Still, the flag doesn't cancel the HTTP request itself. If you want to abort fetch and save backend load, use standard AbortController:

useEffect(() => {
  // Single-use controller for each new request
  const controller = new AbortController();

  async function load() {
    try {
      const url = `/api/search?q=${encodeURIComponent(query)}`;
      const res = await fetch(url, { signal: controller.signal });
      setResults(await res.json());
    } catch (err) {
      // Don't treat an intentional abort as an error
      if (err.name !== 'AbortError') console.error(err);
    }
  }

  load();
  return () => controller.abort();
}, [query]);

On a new query, the browser aborts the previous fetch and throws a DOMException named AbortError. Without checking err.name !== 'AbortError', normal cancellations would trigger your error handler. Create a fresh controller inside each effect since it's single-use, and never make the useEffect callback itself async—otherwise it returns a Promise instead of a cleanup function.

Want a deep diveVotes help us choose what to break down in detail. This material has 0 votes.
Sources · 3