31 lines
713 B
TypeScript
31 lines
713 B
TypeScript
import { useRef, useCallback, useEffect } from 'react';
|
|
|
|
export default function useDebounce<T extends (...args: any[]) => void>(
|
|
fn: T,
|
|
delay: number
|
|
): (...args: Parameters<T>) => void {
|
|
const timeoutRef = useRef<NodeJS.Timeout | null>(null);
|
|
|
|
const debounceFn = useCallback(
|
|
(...args: Parameters<T>): void => {
|
|
if (timeoutRef.current) {
|
|
clearTimeout(timeoutRef.current);
|
|
}
|
|
timeoutRef.current = setTimeout(() => {
|
|
fn(...args);
|
|
}, delay);
|
|
},
|
|
[fn, delay]
|
|
);
|
|
|
|
useEffect(() => {
|
|
return () => {
|
|
if (timeoutRef.current) {
|
|
clearTimeout(timeoutRef.current);
|
|
}
|
|
};
|
|
}, []);
|
|
|
|
return debounceFn;
|
|
}
|