UNPKG

beautiful-react-hooks

Version:

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

63 lines (62 loc) 2.27 kB
"use strict"; var __assign = (this && this.__assign) || function () { __assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; 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 isFunction_1 = __importDefault(require("./shared/isFunction")); var defaultOptions = { cancelOnUnmount: true }; /** * An async-utility hook that accepts a callback function and a delay time (in milliseconds), then delays the * execution of the given function by the defined time. */ var useTimeout = function (fn, milliseconds, options) { if (options === void 0) { options = defaultOptions; } var opts = __assign(__assign({}, defaultOptions), (options || {})); var timeout = (0, react_1.useRef)(); var callback = (0, react_1.useRef)(fn); var _a = (0, react_1.useState)(false), isCleared = _a[0], setIsCleared = _a[1]; // the clear method var clear = (0, react_1.useCallback)(function () { if (timeout.current) { clearTimeout(timeout.current); setIsCleared(true); } }, []); // if the provided function changes, change its reference (0, react_1.useEffect)(function () { if ((0, isFunction_1.default)(fn)) { callback.current = fn; } }, [fn]); // when the milliseconds change, reset the timeout (0, react_1.useEffect)(function () { if (typeof milliseconds === 'number') { timeout.current = setTimeout(function () { callback.current(); }, milliseconds); } return clear; }, [milliseconds]); // when component unmount clear the timeout (0, react_1.useEffect)(function () { return function () { if (opts.cancelOnUnmount) { clear(); } }; }, []); return [isCleared, clear]; }; exports.default = useTimeout;