informed
Version:
A lightweight framework and utility for building powerful forms in React applications
45 lines (39 loc) • 1.29 kB
JavaScript
;
Object.defineProperty(exports, '__esModule', { value: true });
var _rollupPluginBabelHelpers = require('../_virtual/_rollupPluginBabelHelpers.js');
var React = require('react');
var useEffectOnce = function useEffectOnce(effect) {
var destroyFunc = React.useRef();
var effectCalled = React.useRef(false);
var renderAfterCalled = React.useRef(false);
// eslint-disable-next-line no-unused-vars
var _useState = React.useState(0),
_useState2 = _rollupPluginBabelHelpers.slicedToArray(_useState, 2);
_useState2[0];
var setVal = _useState2[1];
if (effectCalled.current) {
renderAfterCalled.current = true;
}
React.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();
}
};
}, []);
};
exports.useEffectOnce = useEffectOnce;