import { useRef, useEffect, useCallback, DependencyList } from "react"; type Callback> = (...args: T) => void; const useThrottled = >( callback: Callback, delay: number, dependencies: DependencyList = [] ): ((...args: T) => void) => { const throttleRef = useRef(false); const callbackRef = useRef>(callback); // Update the callback to be used, if it ever changes useEffect(() => { callbackRef.current = callback; }, [callback]); return useCallback>( (...args) => { if (throttleRef.current) return; throttleRef.current = true; callbackRef.current(...args); setTimeout(() => { throttleRef.current = false; }, delay); }, // eslint-disable-next-line react-hooks/exhaustive-deps [delay, ...dependencies] ); }; export default useThrottled;