UNPKG

@rooks/use-effect-once-when

Version:

Runs a callback effect atmost one time when a condition becomes true

34 lines (30 loc) 1.17 kB
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('react')) : typeof define === 'function' && define.amd ? define(['react'], factory) : (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.useEffectOnceWhen = factory(global.React)); }(this, (function (react) { 'use strict'; /** * useEffectOnceWhen hook * * It fires a callback once when a condition is true or become true. * Fires the callback at most one time. * * @param callback The callback to fire * @param when The condition which needs to be true */ function useEffectOnceWhen(callback, when = true) { const hasRunOnceRef = react.useRef(false); const callbackRef = react.useRef(callback); react.useEffect(() => { callbackRef.current = callback; }); react.useEffect(() => { if (when && !hasRunOnceRef.current) { callbackRef.current(); hasRunOnceRef.current = true; } }, [when]); } return useEffectOnceWhen; }))); //# sourceMappingURL=index.js.map