useState.js 926 B

123456789101112131415161718192021222324252627
  1. import _slicedToArray from "@babel/runtime/helpers/esm/slicedToArray";
  2. import * as React from 'react';
  3. /**
  4. * Same as React.useState but `setState` accept `ignoreDestroy` param to not to setState after destroyed.
  5. * We do not make this auto is to avoid real memory leak.
  6. * Developer should confirm it's safe to ignore themselves.
  7. */
  8. export default function useSafeState(defaultValue) {
  9. var destroyRef = React.useRef(false);
  10. var _React$useState = React.useState(defaultValue),
  11. _React$useState2 = _slicedToArray(_React$useState, 2),
  12. value = _React$useState2[0],
  13. setValue = _React$useState2[1];
  14. React.useEffect(function () {
  15. destroyRef.current = false;
  16. return function () {
  17. destroyRef.current = true;
  18. };
  19. }, []);
  20. function safeSetState(updater, ignoreDestroy) {
  21. if (ignoreDestroy && destroyRef.current) {
  22. return;
  23. }
  24. setValue(updater);
  25. }
  26. return [value, safeSetState];
  27. }