rooks
Version:
Essential React custom hooks ⚓ to super charge your components!
40 lines (39 loc) • 1.43 kB
JavaScript
import { useRef, useEffect } from "react";
import { noop } from "../utils/noop";
/**
* A setTimeout hook that calls a callback after a timeout duration
* when a condition is true
*
* @param callback The callback to be invoked after timeout
* @param timeoutDelayMs Amount of time in ms after which to invoke
* @param when The condition which when true, sets the timeout
* @see https://react-hooks.org/docs/useTimeoutWhen
*/
function useTimeoutWhen(callback, timeoutDelayMs, when) {
if (timeoutDelayMs === void 0) { timeoutDelayMs = 0; }
if (when === void 0) { when = true; }
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) {
// eslint-disable-next-line no-negated-condition
if (typeof window !== "undefined") {
var timeout_1 = window.setTimeout(internalCallback, timeoutDelayMs);
return function () {
window.clearTimeout(timeout_1);
};
}
else {
console.warn("useTimeoutWhen: window is undefined.");
}
}
return noop;
}, [timeoutDelayMs, when]);
}
export { useTimeoutWhen };