Medium JavaScript

React useEffect Cleanup: Fixing Race Conditions with Ignore Flags and AbortController

Search results that flip back to an older query are a useEffect race. Fix stale responses with cleanup, ignore flags and AbortController, and understand StrictMode.

16 Nov, 2026 8 min Updated 23 Oct, 2026 6 Code blocks
Diagram
sequenceDiagram participant U as User participant C as Component participant API as Search API U->>C: types re C->>API: request A for re U->>C: types react C->>C: cleanup aborts A C->>API: request B for react API-->>C: B responds first C->>U: shows results for react API-->>C: A responds late C->>C: ignored, signal aborted

A user types "re" into the product search, pauses, then finishes typing "react". Two requests go out. The one for "re" hits a cold cache and takes 900 ms; the one for "react" comes back in 120 ms. The list shows React results for a moment, then flips to results for "re" and stays there. The input says "react", the list says otherwise, and the bug report reads "search is random sometimes". Nobody can reproduce it on a fast office network.

That is a race condition, and useEffect without a cleanup function makes it the default behaviour. Every effect that starts asynchronous work needs an answer to one question: what happens if this work finishes after the component no longer wants it?

Why the Last Response Wins

Here is the code behind that bug report:

function ProductSearch({ query }: { query: string }) {
  const [results, setResults] = useState<string[]>([]);

  useEffect(() => {
    // BUG: no cleanup. Whichever response arrives LAST wins, not the newest query.
    fetch(`/api/search?q=${encodeURIComponent(query)}`)
      .then((res) => res.json())
      .then((data: string[]) => setResults(data));
  }, [query]);

  return <ResultList items={results} />;
}

Each time query changes, React runs the effect again, but nothing tells the previous run that it is obsolete. Both promises resolve eventually, and setResults is called in arrival order, not request order. On localhost responses arrive in order almost every time, which is why this survives code review and QA.

The same gap causes the other classic: a request that resolves after the component unmounted. React 18 removed the "state update on an unmounted component" warning because it was mostly noise, but the wasted request and any side effects in the .then callback are still real.

Cleanup Functions: Ignore Stale Results

The function you return from an effect runs before the next run of that effect and when the component unmounts. That makes it the place to mark the previous run as stale:

useEffect(() => {
  let ignore = false;

  fetchResults(query).then((data) => {
    if (!ignore) {
      setResults(data);
    }
  });

  return () => {
    ignore = true; // this effect run is stale: the query changed or we unmounted
  };
}, [query]);

Each effect run gets its own ignore variable through the closure. When query changes, React calls the old cleanup (setting the old run's ignore to true) before starting the new run. The late response for "re" still arrives, but it is dropped. This works with any promise-based API, including SDKs that do not accept an abort signal.

AbortController: Cancel the Request Itself

Ignoring a response still lets it download and occupy a connection. When the API accepts an AbortSignal (fetch, axios, most modern SDKs), abort the request instead:

import { useEffect, useState } from 'react';

type SearchState = { results: string[]; loading: boolean; error: Error | null };

export function useSearch(query: string): SearchState {
  const [state, setState] = useState<SearchState>({ results: [], loading: false, error: null });

  useEffect(() => {
    const controller = new AbortController();
    setState((s) => ({ ...s, loading: true, error: null }));

    fetch(`/api/search?q=${encodeURIComponent(query)}`, { signal: controller.signal })
      .then((res) => {
        if (!res.ok) throw new Error(`HTTP ${res.status}`);
        return res.json() as Promise<string[]>;
      })
      .then((results) => {
        if (!controller.signal.aborted) {
          setState({ results, loading: false, error: null });
        }
      })
      .catch((error: unknown) => {
        if (controller.signal.aborted) return; // superseded or unmounted: not an error
        setState((s) => ({ ...s, loading: false, error: error instanceof Error ? error : new Error(String(error)) }));
      });

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

  return state;
}

The flow is the one in the diagram below. Two details matter. First, the guard checks controller.signal.aborted rather than the error name. controller.abort() without arguments rejects fetch with a DOMException named AbortError, but controller.abort(reason) rejects with whatever reason you passed, so a name check silently breaks the day someone adds a reason. Second, the check also runs in .then: abort can happen after the body was already parsed, and the guard keeps a superseded result from being applied.

The Race, Step by Step

sequenceDiagram participant U as User participant C as Component participant API as Search API U->>C: types re C->>API: request A for re U->>C: types react C->>C: cleanup aborts A C->>API: request B for react API-->>C: B responds first C->>U: shows results for react API-->>C: A responds late C->>C: ignored, signal aborted

Request A is aborted the moment the query changes. If the server or the network ignores the cancellation and A still resolves, the aborted guard drops it. Belt and braces: aborting saves bandwidth, the guard guarantees correctness.

StrictMode Runs Your Effect Twice

In development, <StrictMode> mounts every component, unmounts it, and mounts it again. Your effect runs setup, cleanup, setup. This is deliberate: it simulates what happens when React preserves state across a remount and exposes effects that do not clean up after themselves.

// main.tsx: in development StrictMode runs setup -> cleanup -> setup on mount.
createRoot(document.getElementById('root')!).render(
  <StrictMode>
    <App />
  </StrictMode>,
);

// A subscription effect that survives the double run because cleanup undoes setup:
useEffect(() => {
  const socket = connect(roomId);
  socket.on('message', onMessage);
  return () => socket.disconnect();
}, [roomId]);

If you see two requests in the network tab during development, the first one aborted, that is StrictMode doing its job and your cleanup working. Do not "fix" it with a useRef flag that skips the second run. That hides the bug StrictMode is pointing at, and production features that remount components will hit it later. Production builds run effects once per mount.

The rule StrictMode enforces: from the user's point of view, setup followed by cleanup followed by setup must be indistinguishable from a single setup. Subscriptions disconnect, timers clear, requests abort or get ignored.

Testing Race Conditions

Races are hard to reproduce manually, so control the timing in a test. Return deferred promises from a mocked fetch, resolve them out of order, and assert on the final state. Vitest with React Testing Library's renderHook keeps it short:

import { act, renderHook, waitFor } from '@testing-library/react';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { useSearch } from './useSearch';

function deferred<T>() {
  let resolve!: (value: T) => void;
  const promise = new Promise<T>((r) => { resolve = r; });
  return { promise, resolve };
}

describe('useSearch', () => {
  afterEach(() => vi.restoreAllMocks());

  it('ignores a slow response that arrives after a newer one', async () => {
    const slow = deferred<Response>();
    const fast = deferred<Response>();
    const fetchMock = vi.spyOn(globalThis, 'fetch')
      .mockReturnValueOnce(slow.promise)
      .mockReturnValueOnce(fast.promise);

    const { result, rerender } = renderHook(({ q }) => useSearch(q), { initialProps: { q: 're' } });
    rerender({ q: 'react' });

    await act(async () => fast.resolve(Response.json(['react', 'react-dom'])));
    await waitFor(() => expect(result.current.results).toEqual(['react', 'react-dom']));

    await act(async () => slow.resolve(Response.json(['re', 'redux'])));
    expect(result.current.results).toEqual(['react', 'react-dom']);

    const firstSignal = fetchMock.mock.calls[0][1]?.signal;
    expect(firstSignal?.aborted).toBe(true);
  });

  it('aborts the in-flight request on unmount', () => {
    const fetchMock = vi.spyOn(globalThis, 'fetch').mockReturnValue(new Promise(() => {}));
    const { unmount } = renderHook(() => useSearch('vue'));

    unmount();

    expect(fetchMock.mock.calls[0][1]?.signal?.aborted).toBe(true);
  });
});

The first test is the bug report turned into code: the slow response for "re" resolves last and must not overwrite "react". It also checks that the first request's signal was aborted, which proves the cleanup ran. The second test covers unmounting. Neither test relies on real timers or the network, so they run in milliseconds and never flake.

Common Pitfalls

Async effect functions. useEffect(async () => { ... }) returns a promise, not a cleanup function, so React has nothing to call. Define an async function inside the effect and call it, keeping the synchronous return () => ....

Treating AbortError as a failure. Showing an error toast for an aborted request flashes "Something went wrong" every time the user types fast. Check signal.aborted and return quietly.

Sharing one controller across runs. A controller stored in a useRef and reused gets aborted once and then every later request fails immediately. Create a new controller per effect run.

Missing dependencies. If the effect reads query but the dependency array is [], the effect never re-runs, and the cleanup never protects you. Let the react-hooks/exhaustive-deps lint rule do its job.

Cleanup that does not mirror setup. Adding a listener with one function reference and removing it with a new inline arrow removes nothing. Keep the reference and pass the same one to both calls.

When to Use an Effect, and When Not To

Effects are for synchronising with something outside React: the network, a WebSocket, a browser API, a third-party widget. Use one when the component must stay in sync with an external system for as long as it is on screen.

Do not use an effect to derive data from props or state, or to respond to user events:

// Avoid: derived state through an effect (extra render, can go stale)
const [visible, setVisible] = useState<Todo[]>([]);
useEffect(() => setVisible(todos.filter((t) => !t.done)), [todos]);

// Prefer: compute during render (wrap in useMemo only if it is expensive)
const visibleTodos = todos.filter((t) => !t.done);

// Avoid: effect reacting to a flag set by a click
// Prefer: do the work in the event handler that caused it
async function handleSubmit(form: FormValues) {
  await saveOrder(form);
  toast.success('Order saved');
}

Derived values belong in render. Work caused by a click belongs in the click handler, where you know exactly why it ran. For data fetching beyond a few simple cases, a library such as TanStack Query or your framework's data layer (React Server Components, route loaders) handles races, caching, deduplication and retries for you, and is usually the better choice than hand-written fetch effects. When you do write one by hand, give it a cleanup that makes the previous run harmless. That one habit removes a whole category of "random" bugs.

Interactive challenge

Try the challenge

Practice what you just learned. Write your solution, reveal hints if you get stuck.

Instructions

Implement a LatestRequest class that guarantees only the newest request is honoured, like an effect cleanup. begin() aborts the currently active ticket (if any) and returns a new ticket number: 1 for the first call, then 2, 3 and so on, never reused. Aborting a ticket runs every callback registered for it exactly once, in registration order. isCurrent(ticket) in JavaScript / is_current(ticket) in Python returns true only for the active ticket. onAbort(ticket, callback) / on_abort(ticket, callback) stores the callback when the ticket is active, and calls it immediately when the ticket is not active (already superseded or disposed). dispose() aborts the active ticket so that no ticket is current; calling it again does nothing, and begin() keeps working afterwards with the next number.

Starter code

javascript
class LatestRequest {
  constructor() {
    this.counter = 0;
    this.active = null;    // ticket number of the current request, or null
    this.callbacks = [];   // abort callbacks registered for the active ticket
  }

  begin() {
    // TODO: abort the active ticket (run its callbacks once, in order)
    // TODO: return a new ticket number (1, 2, 3, ...) and make it active
    throw new Error('TODO');
  }

  isCurrent(ticket) {
    // TODO: true only for the active ticket
    throw new Error('TODO');
  }

  onAbort(ticket, callback) {
    // TODO: store the callback for the active ticket, call it right away for any other ticket
    throw new Error('TODO');
  }

  dispose() {
    // TODO: abort the active ticket; afterwards no ticket is current
    throw new Error('TODO');
  }
}
python
from typing import Callable


class LatestRequest:
    def __init__(self) -> None:
        self.counter = 0
        self.active: int | None = None  # ticket number of the current request
        self.callbacks: list[Callable[[], None]] = []  # abort callbacks of the active ticket

    def begin(self) -> int:
        # TODO: abort the active ticket (run its callbacks once, in order)
        # TODO: return a new ticket number (1, 2, 3, ...) and make it active
        raise NotImplementedError

    def is_current(self, ticket: int) -> bool:
        # TODO: True only for the active ticket
        raise NotImplementedError

    def on_abort(self, ticket: int, callback: Callable[[], None]) -> None:
        # TODO: store the callback for the active ticket, call it right away for any other ticket
        raise NotImplementedError

    def dispose(self) -> None:
        # TODO: abort the active ticket; afterwards no ticket is current
        raise NotImplementedError

Your solution

Hints

All hints revealed
Hint 1

Keep only the active ticket number and the callbacks of that ticket; older tickets need no storage

Hint 2

Swap the callback list for an empty one before running it, so every callback runs exactly once

Hint 3

begin() and dispose() share the same 'abort the active ticket' step, so put it in one helper

Solution · javascript
class LatestRequest {
  constructor() {
    this.counter = 0;
    this.active = null;    // ticket number of the current request, or null
    this.callbacks = [];   // abort callbacks registered for the active ticket
  }

  begin() {
    this.abortActive();
    this.counter += 1;
    this.active = this.counter;
    return this.active;
  }

  isCurrent(ticket) {
    return this.active !== null && ticket === this.active;
  }

  onAbort(ticket, callback) {
    if (this.isCurrent(ticket)) {
      this.callbacks.push(callback);
    } else {
      callback();
    }
  }

  dispose() {
    this.abortActive();
  }

  abortActive() {
    const callbacks = this.callbacks;
    this.callbacks = [];
    this.active = null;
    for (const cb of callbacks) cb();
  }
}
Solution · python
from typing import Callable


class LatestRequest:
    def __init__(self) -> None:
        self.counter = 0
        self.active: int | None = None  # ticket number of the current request
        self.callbacks: list[Callable[[], None]] = []  # abort callbacks of the active ticket

    def begin(self) -> int:
        self._abort_active()
        self.counter += 1
        self.active = self.counter
        return self.active

    def is_current(self, ticket: int) -> bool:
        return self.active is not None and ticket == self.active

    def on_abort(self, ticket: int, callback: Callable[[], None]) -> None:
        if self.is_current(ticket):
            self.callbacks.append(callback)
        else:
            callback()

    def dispose(self) -> None:
        self._abort_active()

    def _abort_active(self) -> None:
        callbacks, self.callbacks = self.callbacks, []
        self.active = None
        for cb in callbacks:
            cb()

More from JavaScript