UNPKG

throttle-hooks

Version:

Convenient React useDebounce and useThrottle hooks for a clean code.

79 lines (75 loc) 2.75 kB
import { useRef, useState } from 'react'; function useDebounce(wait, leading) { if (wait === void 0) { wait = 400; } if (leading === void 0) { leading = false; } var timer = useRef(null); var func = useRef(null); var _clearTimer = function () { timer.current && clearTimeout(timer.current); timer.current = null; }; var _setFunction = function (newFunction, scope, args) { var _a; // Leading (Call on first) if (leading === true) { func.current = newFunction; // If timer not active, call. if (timer.current === null) (_a = func.current) === null || _a === void 0 ? void 0 : _a.apply(scope, args); _clearTimer(); timer.current = setTimeout(function () { return _clearTimer(); }, wait); } // Default (Call on last) else { _clearTimer(); func.current = newFunction; timer.current = setTimeout(function () { var _a; (_a = func.current) === null || _a === void 0 ? void 0 : _a.apply(scope, args); _clearTimer(); }, wait); } }; return _setFunction; } function useThrottle(wait, leading, trailing) { if (wait === void 0) { wait = 400; } if (leading === void 0) { leading = false; } if (trailing === void 0) { trailing = false; } var timer = useRef(null); var func = useRef(null); var _a = useState(0), previous = _a[0], setPrevious = _a[1]; var _clearTimer = function () { timer.current && clearTimeout(timer.current); timer.current = null; }; var _later = function (scope, args) { var _a; setPrevious(leading === false ? 0 : Date.now()); _clearTimer(); // Call. (_a = func.current) === null || _a === void 0 ? void 0 : _a.apply(scope, args); }; var _setFunction = function (newFunction, scope, args) { var _a; // Fixate current time. var now = Date.now(); // Set new function. func.current = newFunction; if (!previous && leading === false) setPrevious(now); var remaining = wait - (now - previous); if (remaining <= 0 || remaining > wait) { _clearTimer(); setPrevious(now); // Call. (_a = func.current) === null || _a === void 0 ? void 0 : _a.apply(scope, args); } else if (timer.current === null && trailing !== false) { timer.current = setTimeout(function () { return _later(scope, args); }, remaining); } }; return _setFunction; } export { useDebounce, useThrottle }; //# sourceMappingURL=index.mjs.map