The type of the callback function.
The callback function to debounce.
The delay in milliseconds for debouncing.
An object containing:
callback: The debounced function which can be called with the same parameters as the original callback.cancel: A function to cancel any pending invocation of the debounced callback.const { callback, cancel } = useDebouncedCallback((value: string) => {
console.log(value);
}, 300);
// Use `callback` in event handlers or effects
<input onChange={e => callback(e.target.value)} />
// Optionally call `cancel` to cancel pending calls
cancel();
export const useDebouncedCallback = <T extends (...args: any[]) => void>(
fn: T,
wait: number
): {
callback: (...args: Parameters<T>) => void;
cancel: () => void;
} => {
const ref = useRef(withDebounce(fn, wait));
useEffect(() => {
ref.current.cancel();
ref.current = withDebounce(fn, wait);
}, [fn, wait]);
useEffect(() => {
return () => {
ref.current.cancel();
};
}, []);
const callback = useCallback((...args: Parameters<T>) => {
ref.current(...args);
}, []);
const cancel = useCallback(() => {
ref.current.cancel();
}, []);
return {
callback,
cancel
};
};
Custom React hook that returns a debounced version of a callback function. The debounced callback delays invoking the provided function until after the specified wait time has elapsed since the last time the debounced function was called.