UNPKG

@rooks/use-throttle

Version:
36 lines (33 loc) 1.11 kB
import { useState, useRef, useCallback, useEffect } from 'react'; /** * useThrottle * Throttles a function with a timeout and ensures * that the callback function runs at most once in that duration * @param fn The callback to throttle * @param timeout Throttle timeout */ function useThrottle(fn, timeout = 300) { const [ready, setReady] = useState(true); const timerRef = useRef(undefined); if (!fn || typeof fn !== "function") { throw new Error("As a first argument, you need to pass a function to useThrottle hook."); } const throttledFn = useCallback((...args) => { if (!ready) { return; } setReady(false); fn(...args); }, [ready, fn]); useEffect(() => { if (!ready) { timerRef.current = window.setTimeout(() => { setReady(true); }, timeout); return () => window.clearTimeout(timerRef.current); } }, [ready, timeout]); return [throttledFn, ready]; } export default useThrottle; //# sourceMappingURL=index.esm.js.map