@rooks/use-throttle
Version:
A throttle hook for react
42 lines (38 loc) • 1.51 kB
JavaScript
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('react')) :
typeof define === 'function' && define.amd ? define(['react'], factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.useThrottle = factory(global.React));
}(this, (function (react) { 'use strict';
/**
* 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] = react.useState(true);
const timerRef = react.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 = react.useCallback((...args) => {
if (!ready) {
return;
}
setReady(false);
fn(...args);
}, [ready, fn]);
react.useEffect(() => {
if (!ready) {
timerRef.current = window.setTimeout(() => {
setReady(true);
}, timeout);
return () => window.clearTimeout(timerRef.current);
}
}, [ready, timeout]);
return [throttledFn, ready];
}
return useThrottle;
})));
//# sourceMappingURL=index.js.map