Files
latosa-escrima/frontend/hooks/use-debounce.tsx
2025-03-10 16:25:12 +01:00

32 lines
641 B
TypeScript

import React from "react";
export default function useDebounce<T extends (...args: any[]) => void>(
callback: T,
delay: number,
) {
const timeoutRef = React.useRef<NodeJS.Timeout | null>(null);
const debouncedFunction = React.useCallback(
(...args: Parameters<T>) => {
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
}
timeoutRef.current = setTimeout(() => {
callback(...args);
}, delay);
},
[callback, delay],
);
// Cleanup on unmount
React.useEffect(() => {
return () => {
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
}
};
}, []);
return debouncedFunction;
}