Cancel stale requests on dependency change.
Section: Data Fetching Patterns
Fetch with AbortController
tsx
tsx
useEffect(() => {
const controller = new AbortController();
fetch(`/api/search?q=${encodeURIComponent(query)}`, { signal: controller.signal })
.then(r => r.json())
.then(setResults)
.catch(err => {
if (err.name !== 'AbortError') throw err;
});
return () => controller.abort();
}, [query]);Explanation
Aborting requests is cleaner than race flags when the underlying API supports it.
Learn the surrounding workflow
Compare similar commands or jump into common fixes when this command is part of a bigger troubleshooting path.
Related commands
Same sheet · prioritizing Data Fetching Patterns
Expose derived async status
Return a status object from custom data hooks.
Custom hook with options object
Prefer options objects for extensible APIs.