useSyncState.js 661 B

1234567891011121314151617
  1. import _slicedToArray from "@babel/runtime/helpers/esm/slicedToArray";
  2. import * as React from 'react';
  3. export default function useSyncState(defaultState, onChange) {
  4. var stateRef = React.useRef(defaultState);
  5. var _React$useState = React.useState({}),
  6. _React$useState2 = _slicedToArray(_React$useState, 2),
  7. forceUpdate = _React$useState2[1];
  8. function setState(updater) {
  9. var newValue = typeof updater === 'function' ? updater(stateRef.current) : updater;
  10. if (newValue !== stateRef.current) {
  11. onChange(newValue, stateRef.current);
  12. }
  13. stateRef.current = newValue;
  14. forceUpdate({});
  15. }
  16. return [stateRef.current, setState];
  17. }