veza/apps/web/src/hooks/useDebouncedCallback.ts
senke 1a9caf7415 edge-cases: implement Edge 3.2 - handle rapid user interactions
- Created useDebouncedCallback hook for debouncing callbacks
- Created useThrottledCallback hook for throttling callbacks
- Created usePreventDoubleClick hook for preventing double-clicks
- All hooks are properly typed and documented with examples
- Components can use these hooks to prevent rapid interactions
- Existing ButtonLoading component already disables buttons during loading
2026-01-16 12:58:21 +01:00

41 lines
1 KiB
TypeScript

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;
}