Wiring AbortController into useEffect Cleanup
What you'll learn: How to properly connect an AbortController to useEffect's cleanup function so that in-flight fetch requests are cancelled when your component re-renders or unmounts.
The Missing Link
In the previous lesson, you learned about the AbortController API — how it creates a signal you can pass to fetch() and how calling abort() cancels the request. But when should you call abort()? This is where useEffect's cleanup function comes in.
The Pattern
The cleanup function returned from useEffect runs before the effect re-runs (when dependencies change) and when the component unmounts. This timing is perfect for aborting fetch requests that are no longer needed:
useEffect(() => {
const controller = new AbortController();
fetch(url, { signal: controller.signal })
.then(res => res.json())
.then(data => setData(data))
.catch(err => {
if (err.name !== 'AbortError') {
setError(err);
}
});
// Cleanup: abort the request
return () => {
controller.abort();
};
}, [url]);
Why This Works
When url changes (triggering a new search), React runs your cleanup function first, aborting the previous fetch. Then it runs the effect again with the new URL. If the component unmounts while a fetch is in progress, the cleanup aborts it, preventing the "setting state after unmount" warning.
The .catch() checks for 'AbortError' because aborted fetches throw this specific error — you usually don't want to treat cancellation as a real error.
Key Takeaway: Return a cleanup function from useEffect that calls controller.abort() to cancel fetch requests when dependencies change or the component unmounts, preventing race conditions and stale data updates.