rooks
Version:
Essential React custom hooks ⚓ to super charge your components!
40 lines (39 loc) • 1.35 kB
JavaScript
import { useState, useEffect, useCallback, useRef } from "react";
import { noop } from "../utils/noop";
/**
* useThrottle
* Throttles a function with a timeout and ensures
* that the callback function runs at most once in that duration
*
* @param callback The callback to throttle
* @param timeout Throttle timeout
* @returns [Callback, isReady] The throttled callback and if it is currently throttled
* @see https://react-hooks.org/docs/useThrottle
*/
function useThrottle(callback, timeout) {
if (timeout === void 0) { timeout = 300; }
var _a = useState(true), ready = _a[0], setReady = _a[1];
var timerRef = useRef(undefined);
var throttledFunction = useCallback(function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
if (!ready) {
return;
}
setReady(false);
callback.apply(void 0, args);
}, [ready, callback]);
useEffect(function () {
if (!ready) {
timerRef.current = window.setTimeout(function () {
setReady(true);
}, timeout);
return function () { return window.clearTimeout(timerRef.current); };
}
return noop;
}, [ready, timeout]);
return [throttledFunction, ready];
}
export { useThrottle };