Summary
Cancel in-flight fetch when component unmounts, route changes, or new search supersedes old. Pass signal to fetch; catch AbortError separately from real errors. Link abort to React effect cleanup. Without abort: setState on unmounted component and race conditions.
Code example
const controller = new AbortController();
fetch('/api/search?q=react', { signal: controller.signal })
.then((r) => r.json())
.catch((err) => {
if (err.name === 'AbortError') return;
throw err;
});
controller.abort(); // cancels in-flight request
Key points
- Cancel in-flight fetch when component unmounts, route changes, or new search supersedes old.
- Pass
signalto fetch; catchAbortErrorseparately from real errors. - Link abort to React effect cleanup.
- Without abort: setState on unmounted component and race conditions.