UNPKG

rooks

Version:

Essential React custom hooks ⚓ to super charge your components!

39 lines (38 loc) 1.47 kB
import { useRef, useEffect } from "react"; import { noop } from "../utils/noop"; /** * A setInterval hook that calls a callback after a interval duration * when a condition is true * * @param callback The callback to be invoked after interval * @param intervalDurationMs Amount of time in ms after which to invoke * @param when The condition which when true, sets the interval * @param startImmediate If the callback should be invoked immediately * @see https://react-hooks.org/docs/useIntervalWhen */ function useIntervalWhen(callback, intervalDurationMs, when, startImmediate) { if (intervalDurationMs === void 0) { intervalDurationMs = 0; } if (when === void 0) { when = true; } if (startImmediate === void 0) { startImmediate = false; } var savedRefCallback = useRef(); useEffect(function () { savedRefCallback.current = callback; }); function internalCallback() { var _a; (_a = savedRefCallback.current) === null || _a === void 0 ? void 0 : _a.call(savedRefCallback); } useEffect(function () { if (when) { if (startImmediate) { internalCallback(); } var interval_1 = window.setInterval(internalCallback, intervalDurationMs); return function () { window.clearInterval(interval_1); }; } return noop; }, [when, intervalDurationMs, startImmediate]); } export { useIntervalWhen };