javascript / intermediate
Snippet
Cancelling Fetch Requests with AbortController
Using AbortController prevents race conditions and memory leaks by cancelling network requests when a Next.js component unmounts.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
useEffect(() => {const controller = new AbortController();fetch('/api/data', { signal: controller.signal }).then(res => res.json()).catch(err => {if (err.name === 'AbortError') console.log('Fetch aborted');});return () => controller.abort();}, []);
nextjs
Breakdown
1
const controller = new AbortController();
Creates an instance to control and signal the cancellation of the request.
2
return () => controller.abort();
Cleanup function that aborts the request if the component re-renders or unmounts.