use-sync-external-store-with-selector.production.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. /**
  2. * @license React
  3. * use-sync-external-store-with-selector.production.js
  4. *
  5. * Copyright (c) Meta Platforms, Inc. and affiliates.
  6. *
  7. * This source code is licensed under the MIT license found in the
  8. * LICENSE file in the root directory of this source tree.
  9. */
  10. "use strict";
  11. var React = require("react");
  12. function is(x, y) {
  13. return (x === y && (0 !== x || 1 / x === 1 / y)) || (x !== x && y !== y);
  14. }
  15. var objectIs = "function" === typeof Object.is ? Object.is : is,
  16. useSyncExternalStore = React.useSyncExternalStore,
  17. useRef = React.useRef,
  18. useEffect = React.useEffect,
  19. useMemo = React.useMemo,
  20. useDebugValue = React.useDebugValue;
  21. exports.useSyncExternalStoreWithSelector = function (
  22. subscribe,
  23. getSnapshot,
  24. getServerSnapshot,
  25. selector,
  26. isEqual
  27. ) {
  28. var instRef = useRef(null);
  29. if (null === instRef.current) {
  30. var inst = { hasValue: !1, value: null };
  31. instRef.current = inst;
  32. } else inst = instRef.current;
  33. instRef = useMemo(
  34. function () {
  35. function memoizedSelector(nextSnapshot) {
  36. if (!hasMemo) {
  37. hasMemo = !0;
  38. memoizedSnapshot = nextSnapshot;
  39. nextSnapshot = selector(nextSnapshot);
  40. if (void 0 !== isEqual && inst.hasValue) {
  41. var currentSelection = inst.value;
  42. if (isEqual(currentSelection, nextSnapshot))
  43. return (memoizedSelection = currentSelection);
  44. }
  45. return (memoizedSelection = nextSnapshot);
  46. }
  47. currentSelection = memoizedSelection;
  48. if (objectIs(memoizedSnapshot, nextSnapshot)) return currentSelection;
  49. var nextSelection = selector(nextSnapshot);
  50. if (void 0 !== isEqual && isEqual(currentSelection, nextSelection))
  51. return (memoizedSnapshot = nextSnapshot), currentSelection;
  52. memoizedSnapshot = nextSnapshot;
  53. return (memoizedSelection = nextSelection);
  54. }
  55. var hasMemo = !1,
  56. memoizedSnapshot,
  57. memoizedSelection,
  58. maybeGetServerSnapshot =
  59. void 0 === getServerSnapshot ? null : getServerSnapshot;
  60. return [
  61. function () {
  62. return memoizedSelector(getSnapshot());
  63. },
  64. null === maybeGetServerSnapshot
  65. ? void 0
  66. : function () {
  67. return memoizedSelector(maybeGetServerSnapshot());
  68. }
  69. ];
  70. },
  71. [getSnapshot, getServerSnapshot, selector, isEqual]
  72. );
  73. var value = useSyncExternalStore(subscribe, instRef[0], instRef[1]);
  74. useEffect(
  75. function () {
  76. inst.hasValue = !0;
  77. inst.value = value;
  78. },
  79. [value]
  80. );
  81. useDebugValue(value);
  82. return value;
  83. };