useEffectState.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import _slicedToArray from "@babel/runtime/helpers/esm/slicedToArray";
  2. import useEvent from "rc-util/es/hooks/useEvent";
  3. import * as React from 'react';
  4. import { unstable_batchedUpdates } from 'react-dom';
  5. import channelUpdate from "./channelUpdate";
  6. /**
  7. * Batcher for record any `useEffectState` need update.
  8. */
  9. export function useBatcher() {
  10. // Updater Trigger
  11. var updateFuncRef = React.useRef(null);
  12. // Notify update
  13. var notifyEffectUpdate = function notifyEffectUpdate(callback) {
  14. if (!updateFuncRef.current) {
  15. updateFuncRef.current = [];
  16. channelUpdate(function () {
  17. unstable_batchedUpdates(function () {
  18. updateFuncRef.current.forEach(function (fn) {
  19. fn();
  20. });
  21. updateFuncRef.current = null;
  22. });
  23. });
  24. }
  25. updateFuncRef.current.push(callback);
  26. };
  27. return notifyEffectUpdate;
  28. }
  29. /**
  30. * Trigger state update by `useLayoutEffect` to save perf.
  31. */
  32. export default function useEffectState(notifyEffectUpdate, defaultValue) {
  33. // Value
  34. var _React$useState = React.useState(defaultValue),
  35. _React$useState2 = _slicedToArray(_React$useState, 2),
  36. stateValue = _React$useState2[0],
  37. setStateValue = _React$useState2[1];
  38. // Set State
  39. var setEffectVal = useEvent(function (nextValue) {
  40. notifyEffectUpdate(function () {
  41. setStateValue(nextValue);
  42. });
  43. });
  44. return [stateValue, setEffectVal];
  45. }