arrow_backBACK TO DRILLS
Blue BeltuseeffectPREMIUM
AbortController Custom Hook - Attaching Cancellation to Every Fetch
A team wants every fetch triggered from a component to be cancellable when its effect re-runs or unmounts.
REACT_MODULE // 0x42
function useSearchResults(query) {
const [results, setResults] = useState([]);
useEffect(() => {
const controller = new AbortController();
fetch(/api/search?q=${query}, { signal: controller.signal })
.then(res => res.json())
.then(setResults)
.catch(() => {});
return () => controller.abort();
}, [query]);
return results;
}Why is a new AbortController created inside the effect on every run, rather than one shared controller created once outside the hook?