UNPKG

beautiful-react-hooks

Version:

A collection of beautiful (and hopefully useful) React hooks to speed-up your components and hooks development

32 lines (31 loc) 1.4 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); var react_1 = require("react"); var lodash_debounce_1 = __importDefault(require("lodash.debounce")); var useWillUnmount_1 = __importDefault(require("./useWillUnmount")); var defaultOptions = { leading: false, trailing: true }; /** * Accepts a function and returns a new debounced yet memoized version of that same function that delays * its invoking by the defined time. * If time is not defined, its default value will be 250ms. */ var useDebouncedCallback = function (fn, dependencies, wait, options) { if (wait === void 0) { wait = 600; } if (options === void 0) { options = defaultOptions; } var debounced = (0, react_1.useRef)((0, lodash_debounce_1.default)(fn, wait, options)); (0, react_1.useEffect)(function () { debounced.current = (0, lodash_debounce_1.default)(fn, wait, options); }, [fn, wait, options]); (0, useWillUnmount_1.default)(function () { var _a; (_a = debounced.current) === null || _a === void 0 ? void 0 : _a.cancel(); }); return (0, react_1.useCallback)(debounced.current, dependencies !== null && dependencies !== void 0 ? dependencies : []); }; exports.default = useDebouncedCallback;