1import { useMemo } from 'react'; 2import { useEffect } from 'react'; 3import { useRef } from 'react'; 4 5function debounce(fn, wait) { 6 let timer; 7 return function (...args) { 8 if (timer) { 9 clearTimeout(timer); 10 } 11 timer = setTimeout(() => fn(...args), wait); 12 }; 13} 14 15export function useDebounce(callback) { 16 const ref = useRef; 17 useEffect(() => { 18 ref.current = callback; 19 }, [callback]); 20 21 const debouncedCallback = useMemo(() => { 22 const func = () => { 23 ref.current?.(); 24 }; 25 26 return debounce(func, 1000); 27 }, []); 28 29 return debouncedCallback; 30}