0 day streak
javascript / intermediate
Snippet

Managing Async Lifecycle with AbortController

AbortController allows you to cancel network requests when a component unmounts, preventing memory leaks and unnecessary state updates on unmounted components.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
useEffect(() => {
const controller = new AbortController();
fetch('/api/data', { signal: controller.signal })
.then(r => r.json())
.catch(e => {
if (e.name === 'AbortError') return;
console.error(e);
});
return () => controller.abort();
}, []);
react
Breakdown
1
return () => controller.abort();
The cleanup function triggers the abort signal, effectively canceling the ongoing fetch request.