typescriptbeginner
useDebouncedCallback Hook
Returns a debounced version of a callback that delays execution until the pause in calls.
typescriptPress ⌘/Ctrl + Shift + C to copy
import { useRef, useCallback, useEffect } from 'react';
export function useDebouncedCallback<T extends (...args: unknown[]) => void>(
callback: T,
delay: number
): T {
const callbackRef = useRef(callback);
const timerRef = useRef<ReturnType<typeof setTimeout>>();
useEffect(() => {
callbackRef.current = callback;
}, [callback]);
useEffect(() => {
return () => { if (timerRef.current) clearTimeout(timerRef.current); };
}, []);
return useCallback(
((...args: unknown[]) => {
if (timerRef.current) clearTimeout(timerRef.current);
timerRef.current = setTimeout(() => callbackRef.current(...args), delay);
}) as T,
[delay]
);
}
// Usage:
// const debouncedSearch = useDebouncedCallback((query: string) => {
// fetchResults(query);
// }, 300);Use Cases
- Search input debouncing
- Resize handlers
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
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
Infinite Scroll with Intersection Observer
Load more items as the user scrolls using IntersectionObserver. No external libraries required.
Best for: Feed pagination
#infinite-scroll#intersection-observer
typescriptintermediate
React Intersection Observer Hook
Custom useIntersectionObserver hook for lazy loading, infinite scroll, and scroll animations.
Best for: Lazy loading components when they enter viewport
#react#hooks
typescriptintermediate
useThrottle Hook for Rate Limiting
Throttle rapidly-firing values like scroll or resize events with a configurable delay hook.
Best for: Scroll position tracking
#react#hooks