informed
Version:
A lightweight framework and utility for building powerful forms in React applications
41 lines (37 loc) • 1.17 kB
JavaScript
import { slicedToArray as _slicedToArray } from '../_virtual/_rollupPluginBabelHelpers.js';
import { useRef, useState, useEffect } from 'react';
var useEffectOnce = function useEffectOnce(effect) {
var destroyFunc = useRef();
var effectCalled = useRef(false);
var renderAfterCalled = useRef(false);
// eslint-disable-next-line no-unused-vars
var _useState = useState(0),
_useState2 = _slicedToArray(_useState, 2);
_useState2[0];
var setVal = _useState2[1];
if (effectCalled.current) {
renderAfterCalled.current = true;
}
useEffect(function () {
// only execute the effect first time around
if (!effectCalled.current) {
destroyFunc.current = effect();
effectCalled.current = true;
}
// this forces one render after the effect is run
setVal(function (val) {
return val + 1;
});
return function () {
// if the comp didn't render since the useEffect was called,
// we know it's the dummy React cycle
if (!renderAfterCalled.current) {
return;
}
if (destroyFunc.current) {
destroyFunc.current();
}
};
}, []);
};
export { useEffectOnce };