vaulterm/frontend/hooks/useDebounce.ts

29 lines
593 B
TypeScript
Raw Normal View History

2024-11-15 09:39:35 +00:00
import { useCallback, useRef } from "react";
2024-11-08 18:53:30 +00:00
export const useDebounceCallback = <T extends (...args: any[]) => any>(
callback: T,
delay: number = 300
) => {
const timeoutRef = useRef<NodeJS.Timeout | null>(null);
const clear = useCallback(() => {
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
}
}, []);
const fn = useCallback(
(...args: Parameters<T>) => {
clear();
timeoutRef.current = setTimeout(() => {
timeoutRef.current = null;
callback(...args);
}, delay);
},
[delay, clear]
);
2024-11-15 09:39:35 +00:00
return fn;
2024-11-08 18:53:30 +00:00
};