@appbuckets/react-ui-core
Version:
Core utilities built for AppBuckets React UI Framework
30 lines (27 loc) • 848 B
JavaScript
import { __read } from 'tslib';
import * as React from 'react';
function useMountedState(initialState) {
/** Init the state */
var _a = __read(React.useState(initialState), 2),
state = _a[0],
setStateBase = _a[1];
/** Init a ref to check if component is mounted or not */
var isMounted = React.useRef(false);
/** Change isMounted value on component mount/unmount */
React.useEffect(function () {
isMounted.current = true;
return function () {
isMounted.current = false;
};
}, []);
/** Create a wrap to setState function */
var setState = React.useCallback(function (newState) {
/** Assert component is mount */
if (isMounted.current) {
setStateBase(newState);
}
}, []);
/** Return state and wrapped function */
return [state, setState];
}
export { useMountedState as default };