veza/apps/web/src/hooks/useDebouncedCallback.ts

42 lines
1 KiB
TypeScript
Raw Normal View History

import { useCallback, useRef } from 'react';
/**
* Edge 3.2: Hook for debouncing callback functions
* Prevents rapid successive calls by delaying execution until after a specified delay
*
* @param callback - The function to debounce
* @param delay - Delay in milliseconds (default: 300ms)
* @returns Debounced callback function
*
* @example
* ```typescript
* const handleSearch = useDebouncedCallback((query: string) => {
* performSearch(query);
* }, 500);
*
* // Usage in input
* <input onChange={(e) => handleSearch(e.target.value)} />
* ```
*/
export function useDebouncedCallback<T extends (...args: any[]) => any>(
callback: T,
delay: number = 300,
): T {
const timeoutRef = useRef<NodeJS.Timeout | null>(null);
const debouncedCallback = useCallback(
((...args: Parameters<T>) => {
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
}
timeoutRef.current = setTimeout(() => {
callback(...args);
}, delay);
}) as T,
[callback, delay],
);
return debouncedCallback;
}