javascript / expert
Snippet
Orchestrating Task Cancellation with AbortController
Using AbortController within useEffect ensures that inflight network requests are cancelled if the component unmounts or the URL changes. This prevents race conditions and updating the state of an unmounted component.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
useEffect(() => {const controller = new AbortController();const fetchData = async () => {try {const response = await fetch(url, { signal: controller.signal });const data = await response.json();setState(data);} catch (err) {if (err.name !== 'AbortError') console.error(err);}};fetchData();return () => controller.abort();}, [url]);
react
Breakdown
1
const controller = new AbortController();
Creates a new controller instance to manage the abort signal.
2
signal: controller.signal
Passes the signal to the fetch request, allowing it to be terminated externally.
3
return () => controller.abort();
The cleanup function triggers the abort when the effect re-runs or the component unmounts.