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
* handleSearch(e.target.value)} />
* ```
*/
export function useDebouncedCallback any>(
callback: T,
delay: number = 300,
): T {
const timeoutRef = useRef(null);
const debouncedCallback = useCallback(
((...args: Parameters) => {
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
}
timeoutRef.current = setTimeout(() => {
callback(...args);
}, delay);
}) as T,
[callback, delay],
);
return debouncedCallback;
}