0 day streak
javascript / intermediate
Snippet

Effect Cleanup with AbortController

Using AbortController in useEffect prevents memory leaks and state updates on unmounted components by cancelling pending fetch requests.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
useEffect(() => {
const controller = new AbortController();
async function fetchData() {
try {
const res = await fetch('/api/data', { signal: controller.signal });
const data = await res.json();
setData(data);
} catch (err) {
if (err.name !== 'AbortError') console.error(err);
}
}
fetchData();
return () => controller.abort();
}, [id]);
nextjs
Breakdown
1
signal: controller.signal
Links the fetch request to the abort controller's signal.
2
return () => controller.abort();
The cleanup function triggers when the component unmounts or dependencies change.