UNPKG

rooks

Version:

Essential React custom hooks ⚓ to super charge your components!

43 lines (42 loc) 1.49 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.useThrottle = void 0; var react_1 = require("react"); var noop_1 = require("../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 = (0, react_1.useState)(true), ready = _a[0], setReady = _a[1]; var timerRef = (0, react_1.useRef)(undefined); var throttledFunction = (0, react_1.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]); (0, react_1.useEffect)(function () { if (!ready) { timerRef.current = window.setTimeout(function () { setReady(true); }, timeout); return function () { return window.clearTimeout(timerRef.current); }; } return noop_1.noop; }, [ready, timeout]); return [throttledFunction, ready]; } exports.useThrottle = useThrottle;