0 day streak
javascript / expert
Snippet

Race Condition Prevention with AbortController

When fetching data in useEffect, a race condition occurs if the URL changes before the previous request finishes. AbortController cancels outdated requests in the cleanup phase.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
useEffect(() => {
const controller = new AbortController();
async function fetchData() {
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 a new instance to control the signal for the fetch request.
2
return () => controller.abort();
The cleanup function triggers when the component unmounts or dependencies change.