typescriptbeginner
useTimeout Hook
Declarative setTimeout hook with automatic cleanup and reset capabilities.
typescriptPress ⌘/Ctrl + Shift + C to copy
import { useEffect, useRef, useCallback } from 'react';
export function useTimeout(callback: () => void, delay: number | null) {
const savedCallback = useRef(callback);
const timerRef = useRef<ReturnType<typeof setTimeout>>();
useEffect(() => {
savedCallback.current = callback;
}, [callback]);
const reset = useCallback(() => {
if (timerRef.current) clearTimeout(timerRef.current);
if (delay !== null) {
timerRef.current = setTimeout(() => savedCallback.current(), delay);
}
}, [delay]);
useEffect(() => {
reset();
return () => { if (timerRef.current) clearTimeout(timerRef.current); };
}, [reset]);
return { reset };
}Use Cases
- Auto-dismiss notifications
- Delayed actions
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
typescriptintermediate
useInterval Hook
Declarative setInterval hook that handles cleanup and dynamic delay changes safely.
Best for: Polling APIs
#hooks#timer
typescriptbeginner
usePrevious Hook
Track the previous value of any state or prop using a ref-based hook for comparison logic.
Best for: Detecting value changes
#hooks#state
typescriptintermediate
React Custom Hook for Data Fetching
A reusable useFetch hook with loading states, error handling, caching, and abort support.
Best for: Reusable data fetching across components
#react#hooks
typescriptintermediate
React Form Validation Hook
A type-safe form validation hook with field-level errors, dirty tracking, and submit handling.
Best for: Type-safe form handling without libraries
#react#forms