useState.js 936 B

1234567891011121314151617181920212223242526
  1. /**
  2. * copy from https://github.com/react-component/util/blob/9d5cb8946da29e690bead78b2c251da6f7cbd0eb/src/hooks/useState.ts
  3. */
  4. import * as React from 'functional-mini/compat';
  5. /**
  6. * Same as React.useState but `setState` accept `ignoreDestroy` param to not to setState after destroyed.
  7. * We do not make this auto is to avoid real memory leak.
  8. * Developer should confirm it's safe to ignore themselves.
  9. */
  10. export function useSafeState(defaultValue) {
  11. var destroyRef = React.useRef(false);
  12. var _a = React.useState(defaultValue), value = _a[0], setValue = _a[1];
  13. React.useEffect(function () {
  14. destroyRef.current = false;
  15. return function () {
  16. destroyRef.current = true;
  17. };
  18. }, []);
  19. function safeSetState(updater, ignoreDestroy) {
  20. if (ignoreDestroy && destroyRef.current) {
  21. return;
  22. }
  23. setValue(updater);
  24. }
  25. return [value, safeSetState];
  26. }