import { useRef, useCallback, useEffect } from 'react' export const useDebounce = ( fn: (...args: Args) => void, delay: number ): ((...args: Args) => void) => { const timeoutRef = useRef(null) const debouncedFn = useCallback( (...args: Args) => { if (timeoutRef.current) clearTimeout(timeoutRef.current) timeoutRef.current = setTimeout(() => { fn(...args) }, delay) }, [fn, delay] ) useEffect(() => { return () => { if (timeoutRef.current) { clearTimeout(timeoutRef.current) } } }, []) return debouncedFn }