hardRace ConditionsReact

The race to render

A developer asked an AI assistant to fetch search results as the user types in a live search box. The suggested code works well on a fast connection, but on a throttled network, older searches sometimes overwrite newer ones with stale results.

LiveSearch.jsx
function LiveSearch() {
  const [results, setResults] = useState([]);

  const handleChange = async (e) => {
    const query = e.target.value;
    const res = await fetch(`/api/search?q=${query}`);
    const data = await res.json();
    setResults(data);
  };

  return <input onChange={handleChange} />;
}

A user quickly types 'r', then 'react'. The request for 'r' is slow and resolves after the request for 'react'. What does the results list show?

The results for 'react': React automatically cancels in-flight requests triggered by the same input.
A merged list combining both 'r' and 'react' results.
The results for 'r': whichever fetch resolves last wins and overwrites state, regardless of which query was actually typed most recently.
An empty list, because two overlapping fetches from the same component always throw.

Sign in with GitHub to submit an answer and track your progress.