@jk-core/hooks
Version:
hooks for jk
34 lines (26 loc) • 888 B
text/typescript
import { useCallback, useEffect, useRef } from 'react';
/* eslint-disable @typescript-eslint/no-explicit-any */
type Procedure = (...args: any[]) => void;
const useDebounce = (func: Procedure, delay: number): Procedure => {
const funcRef = useRef(func);
const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
// 매 렌더링마다 func가 바뀔 수 있으니 ref에 최신 함수 저장
useEffect(() => {
funcRef.current = func;
return () => {
if (timeoutRef.current !== null) {
clearTimeout(timeoutRef.current);
}
};
}, [func]);
const debouncedFn = useCallback((...args: any[]) => {
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
}
timeoutRef.current = setTimeout(() => {
funcRef.current(...args);
}, delay);
}, [delay]);
return debouncedFn;
};
export default useDebounce;