Prevent stale request results
A slower old request can arrive after a newer one
Suppose a user selects Minerals and immediately selects Fossils. If Minerals is slower, its response can arrive last. Updating the same result state from both operations can display the wrong collection. This is a race condition: an outcome depends on the order of asynchronous completions. A request identity or a per-Effect cleanup guard prevents a superseded result from committing to current UI. Cancellation can also avoid wasted work if the client supports it.
import React from 'react';function isCurrent(completedId, latestId) { return completedId === latestId;}export default function App() { const latestId = 2; const arrivals = [{id:2,name:'Fossils'}, {id:1,name:'Minerals'}]; const accepted = arrivals.filter(entry => isCurrent(entry.id, latestId)); return <main><h1>Accepted result</h1><p>{accepted.map(entry => entry.name).join(', ')}</p></main>;}Expected: Fossils. This is an offline model of completion order, not a real asynchronous React test. In an event-driven request manager, assign a new monotonically increasing ID to each request and compare the captured ID against the latest ID when it settles. A collection name alone is not unique if the user selects A, then B, then A again.
Ignore results when an Effect no longer owns them
import React, { useEffect, useState } from 'react';function readCollection(name) { return new Promise(resolve => setTimeout(() => resolve(name === 'minerals' ? ['Quartz'] : ['Ammonite']), name === 'minerals' ? 350 : 50));}function Collection({ name }) { const [result,setResult] = useState({status:'loading'}); useEffect(() => { let active = true; readCollection(name).then(items => { if (active) setResult({status:'success',items}); }, () => { if (active) setResult({status:'error'}); }); return () => { active = false; }; }, [name]); return <p role="status">{result.status === 'success' ? result.items.join(', ') : result.status === 'error' ? 'Unavailable' : 'Loading…'}</p>;}export default function App() { const [name,setName] = useState('minerals'); return <main><label>Collection <select value={name} onChange={e => setName(e.target.value)}><option value="minerals">Minerals</option><option value="fossils">Fossils</option></select></label> <Collection key={name} name={name} /></main>;}Switch quickly to Fossils; the expected settled text is Ammonite. Each selection is keyed here to reset the child to loading before its Effect executes. In other designs, preserve the component and store the request key alongside the result; do not show a previous query as a new query result. The active variable is local to each setup, not a shared flag. Cleanup makes a previous setup unable to update its state, including the development StrictMode cleanup/setup cycle. The mock timer still runs to completion: ignoring a result is not cancellation.
Pass an AbortSignal to a cooperating client
import React, { useEffect, useState } from 'react';function delayedRead(signal) { return new Promise((resolve,reject) => { if (signal.aborted) { reject(signal.reason); return; } function onAbort() { clearTimeout(timer); reject(signal.reason); } const timer = setTimeout(() => { signal.removeEventListener('abort',onAbort); resolve('Quartz'); }, 500); signal.addEventListener('abort',onAbort,{once:true}); });}export default function App() { const [running,setRunning] = useState(true); return <main><button type="button" disabled={!running} onClick={() => setRunning(false)}>Cancel</button> {running ? <Readout /> : <p role="status">Cancelled.</p>}</main>;}function Readout() { const [message,setMessage] = useState('Loading…'); useEffect(() => { const request = new AbortController(); let active = true; delayedRead(request.signal).then(value => { if (active) setMessage(value); }, () => { if (active) setMessage('Unable to load.'); }); return () => { active = false; request.abort(); }; }, []); return <p role="status">{message}</p>;}Cancel before the timer completes: the Readout unmounts and its cleanup aborts its own request; Cancelled replaces it. Without cancellation, Quartz is the expected final text. The AbortController creates a signal that cooperating asynchronous work can observe. The real fetch API accepts a signal in its options. The client must implement cancellation; an abort does not guarantee that a remote server has undone work. For a real fetch, handle rejection after abort separately from errors and guard stale continuations after parsing. Never reuse an already aborted signal for a fresh request.
Practice
Draw the completion order for A, B and A again. Explain why using a name as a request ID is insufficient. Test the guard and then cancel before and after the delay in an approved browser fixture.