Blog

Fix a React useEffect race condition with AbortController

The search box says react, but the results are for re. If every keystroke starts a fetch, the earlier request can finish last and overwrite the newer results. Give each useEffect run its own AbortController, abort it in cleanup, and check signal.aborted before writing either results or errors to state.

If an AI coding agent built the search box, inspect what runs after await. A patch that adds debouncing can pass a quick demo and still leave that code writing stale results.

Confirm the requests finished out of order

Open the browser's Network panel and filter for /api/search. Change re to react while the first request is still pending. Check the query string and completion time for each request. If react finishes first and the UI switches back to re when the older request finishes, the last response to arrive is winning.

Network throttling can make the overlap easier to see. For a regression test, hold the requests open and release them in the order you choose.

Cancel the old fetch in useEffect cleanup

This example expects GET /api/search?q=... to return a JSON array of strings. Save the request code as search-request.mjs. It accepts a replacement for fetch so the test can control the order in which the requests finish.

export async function runSearch(query, signal, publish, request = fetch) {
  const params = new URLSearchParams({ q: query });
  let outcome;

  try {
    const response = await request(`/api/search?${params}`, { signal });
    if (!response.ok) {
      throw new Error(`Search failed (${response.status})`);
    }
    const items = await response.json();
    outcome = { query, items };
  } catch (error) {
    outcome = { query, error: error.message };
  }

  if (!signal.aborted) publish(outcome);
}

Call it from SearchResults.jsx once per trimmed query. Put the controller inside the effect so each request owns its cancellation signal.

import { useEffect, useState } from 'react';
import { runSearch } from './search-request.mjs';

export default function SearchResults({ text }) {
  const query = text.trim();
  const [settled, setSettled] = useState(null);

  useEffect(() => {
    if (!query) return;

    const controller = new AbortController();
    void runSearch(query, controller.signal, setSettled);
    return () => controller.abort();
  }, [query]);

  if (!query) return <p>Type to search.</p>;
  if (settled?.query !== query) return <p role="status">Searching...</p>;
  if ('error' in settled) return <p role="alert">{settled.error}</p>;
  if (settled.items.length === 0) return <p>No results.</p>;

  return (
    <ul>
      {settled.items.map((item, index) => <li key={index}>{item}</li>)}
    </ul>
  );
}

React cleans up the previous effect before starting the next one and again when the component unmounts. The render checks which query produced the saved result, so a result for a different query stays hidden even before cleanup runs. React Strict Mode also runs an extra setup and cleanup on initial mount in development, which can show up as a canceled request. React useEffect reference

Passing the signal to fetch lets the browser cancel the request or stop reading the response body. The final check also covers async work that ignores the signal, such as a custom request wrapper. Put that check after the last await, where it can guard both success and failure. An HTTP error such as 503 arrives as a response, so check response.ok before reading it as search results. Fetch Standard

Test stale results and stale errors without sleeps

Save this as search-request.test.mjs next to search-request.mjs. The fake request deliberately keeps running after abort. It tests whether the application can ignore a late result even when the request layer still delivers one.

import assert from 'node:assert/strict';
import test from 'node:test';
import { runSearch } from './search-request.mjs';

for (const late of ['success', 'failure']) {
  test(`ignore an old request that ends in ${late}`, async () => {
    const pending = new Map();
    const published = [];
    const publish = value => published.push(value);
    const request = (url, { signal }) => new Promise((resolve, reject) => {
      pending.set(url, { resolve, reject, signal });
    });

    const oldController = new AbortController();
    const old = runSearch('re', oldController.signal, publish, request);
    oldController.abort();
    const current = runSearch('react', new AbortController().signal, publish, request);

    pending.get('/api/search?q=react').resolve(Response.json(['React']));
    await current;

    const oldRequest = pending.get('/api/search?q=re');
    assert.equal(oldRequest.signal.aborted, true);
    if (late === 'success') {
      oldRequest.resolve(Response.json(['Redis']));
    } else {
      oldRequest.reject(new Error('Connection lost'));
    }
    await old;

    assert.deepEqual(published, [{ query: 'react', items: ['React'] }]);
  });
}

test('show an HTTP error for the current query', async () => {
  const published = [];
  await runSearch(
    'react',
    new AbortController().signal,
    value => published.push(value),
    async () => new Response(null, { status: 503 }),
  );
  assert.deepEqual(published, [{ query: 'react', error: 'Search failed (503)' }]);
});

Run the test with Node's built-in test runner. Node.js test runner docs

node --test search-request.test.mjs

All three tests should pass. In the example file, temporarily change if (!signal.aborted) publish(outcome); to publish(outcome); and run the test again. Both stale-response cases should fail while the current-query error still passes. Restore the guard afterward.

Give your coding agent an acceptance test

Describe the order you need the agent to reproduce. Keep the old-request failure in the test as well as the old-request success. A patch can guard setResults and still let an obsolete catch or finally change what the user sees.

Fix stale results in the React search component. In the test, start a
request for `re`, switch to `react`, and let `react` finish first.
Then finish `re` with a success in one case and an error in another.
The screen should still show the `react` results in both cases.
Use controlled promises and keep error reporting for the current query.

If the agent says the test covers the bug, try removing the guard once and see it fail. The same check catches other weak tests from coding agents. How to test AI-generated code