AbortController for Cleanup
Create an AbortController, pass its signal to fetch, and cancel in-flight requests in the cleanup function to prevent state updates on unmounted components.
Why Cancel Fetch Requests?
When a component unmounts or re-fetches, the previous request may still be in flight. If it resolves after the new request, stale data overwrites fresh data. AbortController cancels in-flight requests cleanly.
AbortController Basics
Create an AbortController, pass its signal to fetch, and call controller.abort() to cancel. Fetch throws an AbortError when aborted.
const controller = new AbortController();
try {
const res = await fetch('/api/data', { signal: controller.signal });
const data = await res.json();
setData(data);
} catch (err) {
if (err instanceof DOMException && err.name === 'AbortError') {
console.log('Request was cancelled');
} else {
setError((err as Error).message);
}
}
// To cancel:
controller.abort();All lessons in this course
- useEffect Basics: Dependencies and Cleanup
- Fetching Data on Mount
- Handling Loading and Error States
- AbortController for Cleanup