UNPKG

1.27 kBJavaScriptView Raw
1"use strict";
2
3var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
4var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
5Object.defineProperty(exports, "__esModule", {
6 value: true
7});
8exports.default = useSafeState;
9var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));
10var React = _interopRequireWildcard(require("react"));
11/**
12 * Same as React.useState but `setState` accept `ignoreDestroy` param to not to setState after destroyed.
13 * We do not make this auto is to avoid real memory leak.
14 * Developer should confirm it's safe to ignore themselves.
15 */
16function useSafeState(defaultValue) {
17 var destroyRef = React.useRef(false);
18 var _React$useState = React.useState(defaultValue),
19 _React$useState2 = (0, _slicedToArray2.default)(_React$useState, 2),
20 value = _React$useState2[0],
21 setValue = _React$useState2[1];
22 React.useEffect(function () {
23 destroyRef.current = false;
24 return function () {
25 destroyRef.current = true;
26 };
27 }, []);
28 function safeSetState(updater, ignoreDestroy) {
29 if (ignoreDestroy && destroyRef.current) {
30 return;
31 }
32 setValue(updater);
33 }
34 return [value, safeSetState];
35}
\No newline at end of file