javascript / expert
Snippet
Race Condition Prevention via AbortController in Hooks
Using AbortController inside useEffect is critical for preventing race conditions. When the dependency changes or the component unmounts, we cancel the ongoing fetch. This ensures that a late-arriving response from an old request doesn't overwrite the state of a newer request.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
useEffect(() => {const controller = new AbortController();const fetchData = async () => {try {const response = await fetch(url, { signal: controller.signal });const data = await response.json();setData(data);} catch (err) {if (err.name === 'AbortError') return;console.error('Fetch error:', err);}};fetchData();return () => controller.abort();}, [url]);
react
Breakdown
1
const controller = new AbortController();
Creates an instance to control and signal the cancellation of web requests.
2
signal: controller.signal
Passes the abort signal to the fetch options to make it cancellable.
3
return () => controller.abort();
Cleanup function that runs before the next effect or on unmount, triggering the cancellation.