UNPKG

1.76 kBJavaScriptView Raw
1import { invariant } from "../../utilities/globals/index.js";
2import * as React from 'react';
3import { canUseLayoutEffect } from "../../utilities/index.js";
4var didWarnUncachedGetSnapshot = false;
5var uSESKey = "useSyncExternalStore";
6var realHook = React[uSESKey];
7export var useSyncExternalStore = realHook || (function (subscribe, getSnapshot, getServerSnapshot) {
8 var value = getSnapshot();
9 if (__DEV__ &&
10 !didWarnUncachedGetSnapshot &&
11 value !== getSnapshot()) {
12 didWarnUncachedGetSnapshot = true;
13 __DEV__ && invariant.error('The result of getSnapshot should be cached to avoid an infinite loop');
14 }
15 var _a = React.useState({ inst: { value: value, getSnapshot: getSnapshot } }), inst = _a[0].inst, forceUpdate = _a[1];
16 if (canUseLayoutEffect) {
17 React.useLayoutEffect(function () {
18 Object.assign(inst, { value: value, getSnapshot: getSnapshot });
19 if (checkIfSnapshotChanged(inst)) {
20 forceUpdate({ inst: inst });
21 }
22 }, [subscribe, value, getSnapshot]);
23 }
24 else {
25 Object.assign(inst, { value: value, getSnapshot: getSnapshot });
26 }
27 React.useEffect(function () {
28 if (checkIfSnapshotChanged(inst)) {
29 forceUpdate({ inst: inst });
30 }
31 return subscribe(function handleStoreChange() {
32 if (checkIfSnapshotChanged(inst)) {
33 forceUpdate({ inst: inst });
34 }
35 });
36 }, [subscribe]);
37 return value;
38});
39function checkIfSnapshotChanged(_a) {
40 var value = _a.value, getSnapshot = _a.getSnapshot;
41 try {
42 return value !== getSnapshot();
43 }
44 catch (_b) {
45 return true;
46 }
47}
48//# sourceMappingURL=useSyncExternalStore.js.map
\No newline at end of file