javascript / expert
Snippet
AbortSignal Integration for Cancelable Async Side Effects in React Hooks
This expert-level React hook manages asynchronous lifecycle events safely using `AbortController` and `AbortSignal`. It prevents race conditions and memory leaks by explicitly canceling pending HTTP requests when the component unmounts or dependencies change, while filtering out benign `AbortError` instances from application state errors.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import { useState, useEffect, useRef } from 'react';export function useCancelableFetch(url) {const [data, setData] = useState(null);const [error, setError] = useState(null);const abortControllerRef = useRef(null);useEffect(() => {abortControllerRef.current?.abort('Component unmounted or URL changed');const controller = new AbortController();abortControllerRef.current = controller;async function executeFetch() {try {const response = await fetch(url, { signal: controller.signal });if (!response.ok) throw new Error(`HTTP Error ${response.status}`);const json = await response.json();setData(json);} catch (err) {if (err.name !== 'AbortError') {setError(err);}}}executeFetch();return () => controller.abort('Cleanup triggered');}, [url]);return { data, error };}
react
Breakdown
1
const controller = new AbortController();
Instantiates a native JS AbortController to issue cancellation signals to fetch requests.
2
const response = await fetch(url, { signal: controller.signal });
Binds the controller's AbortSignal directly to the fetch request options.
3
if (err.name !== 'AbortError') { setError(err); }
Differentiates operational runtime errors from intentional fetch cancellations to avoid unnecessary error states.
4
return () => controller.abort('Cleanup triggered');
Triggers the abort signal during effect teardown when dependencies update or unmounting occurs.