27 lines
926 B
JavaScript
27 lines
926 B
JavaScript
import _slicedToArray from "@babel/runtime/helpers/esm/slicedToArray";
|
|
import * as React from 'react';
|
|
/**
|
|
* Same as React.useState but `setState` accept `ignoreDestroy` param to not to setState after destroyed.
|
|
* We do not make this auto is to avoid real memory leak.
|
|
* Developer should confirm it's safe to ignore themselves.
|
|
*/
|
|
export default function useSafeState(defaultValue) {
|
|
var destroyRef = React.useRef(false);
|
|
var _React$useState = React.useState(defaultValue),
|
|
_React$useState2 = _slicedToArray(_React$useState, 2),
|
|
value = _React$useState2[0],
|
|
setValue = _React$useState2[1];
|
|
React.useEffect(function () {
|
|
destroyRef.current = false;
|
|
return function () {
|
|
destroyRef.current = true;
|
|
};
|
|
}, []);
|
|
function safeSetState(updater, ignoreDestroy) {
|
|
if (ignoreDestroy && destroyRef.current) {
|
|
return;
|
|
}
|
|
setValue(updater);
|
|
}
|
|
return [value, safeSetState];
|
|
} |