Skip to content

react-async-race ​

An effect that sets state after its async work finishes (after an await, or in .then), and neither aborts that work nor returns a cleanup.

Why: React runs the effect again every time its dependencies change, and each run waits on its own. Switch from user A to user B quickly and two requests are in flight; if the one for A is slower, it finishes last and its answer replaces B's. Nothing crashes: the page just shows the wrong user. Guide: React.

✕ Rejectedreact-async-race
tsx
import { useEffect, useState } from "react";

async function search(query: string): Promise<readonly string[]> {
  return query === "" ? [] : [query];
}

export function Results({ query }: { query: string }) {
  const [results, setResults] = useState<readonly string[]>([]);
  useEffect(() => {
    const load = async (): Promise<void> => {
      const found = await search(query);
      setResults(found);
    };
    void load();
  }, [query]);
  return <ul>{results.map((r) => <li key={r}>{r}</li>)}</ul>;
}

✅ Accepted: useTask aborts the previous run, and keeps the outcome in one value

✓ Accepted0 diagnostics
tsx
import { useEffect } from "react";
import { type Enum, match } from "@evobug_com/safe-ts-std/enum";
import type { Result } from "@evobug_com/safe-ts-std/result";
import { Match } from "@evobug_com/safe-ts-react/match";
import { useTask } from "@evobug_com/safe-ts-react/task";

type SearchError = Enum<{ Offline: {}; Refused: { status: number } }>;

declare function search(query: string, signal: AbortSignal): Promise<Result<readonly string[], SearchError>>;

export function Results({ query }: { query: string }) {
  const { state, run } = useTask((signal, q: string) => search(q, signal));
  useEffect(() => {
    run(query).catch((reason: unknown) => console.error(reason));
  }, [query, run]);
  return (
    <Match
      on={state}
      Ready={({ value }) => <ul>{value.map((r) => <li key={r}>{r}</li>)}</ul>}
      Failed={({ error }) => (
        <p>
          {match(error, {
            Offline: () => "You're offline.",
            Refused: ({ status }) => `The server refused the search (${status}).`,
          })}
        </p>
      )}
      _={() => <p>Searching…</p>}
    />
  );
}

Each run aborts the previous run's signal, only the latest run sets state, and the run in progress is aborted when the component unmounts.

✅ Also accepted: the cleanup stops the run the next one replaces, when the result isn't kept as an AsyncState

✓ Accepted0 diagnostics
tsx
import { useEffect, useState } from "react";

async function search(query: string, signal: AbortSignal): Promise<readonly string[]> {
  return signal.aborted || query === "" ? [] : [query];
}

export function Results({ query }: { query: string }) {
  const [results, setResults] = useState<readonly string[]>([]);
  useEffect(() => {
    const controller = new AbortController();
    const load = async (): Promise<void> => {
      const found = await search(query, controller.signal);
      if (!controller.signal.aborted) setResults(found);
    };
    void load();
    return () => controller.abort();
  }, [query]);
  return <ul>{results.map((r) => <li key={r}>{r}</li>)}</ul>;
}

React calls the cleanup before the effect runs again, and when the component unmounts. An ignore flag the cleanup sets (let ignore = false; ... return () => { ignore = true; };, checked before setting state) works too.

These count as cancelling: the effect returns a function (or a name bound to one), or uses an AbortController or a signal. A setter passed to .then (.then(setResults)) is a write after the promise settles, like one after await.

This rule is about an answer that arrives late, whatever the run read. A value read from shared state before the await and written back from it (a lost update), or a check made before it and acted on after it, is stale-across-await's: the two report different writes.

What the rule can't see: whether the cleanup it found really stops this request (any returned function counts), and state set by a function declared outside the effect that the effect calls. Async work started from an event handler (search-as-you-type in onChange) can race the same way; the rule only looks at effects.

MIT OR Apache-2.0 · Docs by Gemini 4 Neon Extra