typescriptbeginner
useAbortController Hook
Creates and manages AbortController instances for cancelling fetch requests on unmount.
typescriptPress ⌘/Ctrl + Shift + C to copy
import { useRef, useEffect, useCallback } from 'react';
export function useAbortController() {
const controllerRef = useRef<AbortController | null>(null);
const getSignal = useCallback(() => {
if (controllerRef.current) {
controllerRef.current.abort();
}
controllerRef.current = new AbortController();
return controllerRef.current.signal;
}, []);
const abort = useCallback(() => {
controllerRef.current?.abort();
}, []);
useEffect(() => {
return () => {
controllerRef.current?.abort();
};
}, []);
return { getSignal, abort };
}
// Usage:
// const { getSignal } = useAbortController();
// const res = await fetch('/api/data', { signal: getSignal() });Use Cases
- Cancelling stale requests
- Search-as-you-type
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
typescriptintermediate
useFetch — Generic Data Fetching Hook
Custom React hook for data fetching with loading, error, and refetch states using the Fetch API.
Best for: API data fetching
#hooks#fetch
typescriptadvanced
useFetch with Cache Hook
Data fetching hook with built-in cache, loading, error states, and automatic revalidation.
Best for: API data fetching
#hooks#fetch
typescriptbeginner
useDebounce — Debounced Value Hook
Debounce any rapidly-changing value with a configurable delay. Useful for search inputs and resize handlers.
Best for: Search-as-you-type
#hooks#debounce
typescriptintermediate
useLocalStorage — Persistent State Hook
Sync React state with localStorage including SSR safety, JSON serialization, and cross-tab updates.
Best for: User preferences
#hooks#localstorage