UNPKG

beautiful-react-hooks

Version:

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

60 lines (59 loc) 2.11 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); }; Object.defineProperty(exports, "__esModule", { value: true }); var react_1 = require("react"); var defaultOptions = { cancelOnUnmount: true, }; /** * An async-utility hook that accepts a callback function and a delay time (in milliseconds), then repeats the * execution of the given function by the defined milliseconds. */ var useInterval = 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) { setIsCleared(true); clearInterval(timeout.current); } }, []); // if the provided function changes, change its reference (0, react_1.useEffect)(function () { if (typeof fn === 'function') { callback.current = fn; } }, [fn]); // when the milliseconds change, reset the timeout (0, react_1.useEffect)(function () { if (typeof milliseconds === 'number') { timeout.current = setInterval(function () { callback.current(); }, milliseconds); } // cleanup previous interval 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 = useInterval;