Skip to content

Commit

Permalink
Assorted useSyncExternalStore refinements (#9709)
Browse files Browse the repository at this point in the history
  • Loading branch information
benjamn authored May 12, 2022
1 parent e89febf commit 06cf0b8
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 14 deletions.
8 changes: 5 additions & 3 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,6 @@
},
"dependencies": {
"@graphql-typed-document-node/core": "^3.1.1",
"@types/use-sync-external-store": "^0.0.3",
"@wry/context": "^0.6.0",
"@wry/equality": "^0.5.0",
"@wry/trie": "^0.3.0",
Expand Down Expand Up @@ -109,6 +108,7 @@
"@types/node": "16.11.33",
"@types/react": "17.0.45",
"@types/react-dom": "17.0.16",
"@types/use-sync-external-store": "^0.0.3",
"acorn": "8.7.1",
"bundlesize": "0.18.1",
"cross-fetch": "3.1.5",
Expand Down
19 changes: 9 additions & 10 deletions src/react/hooks/useSyncExternalStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,22 +12,21 @@ type RealUseSESHookType =
// when only React 17 or earlier is installed.
typeof import("use-sync-external-store").useSyncExternalStore;

// Prevent webpack from complaining about our feature detection of the
// useSyncExternalStore property of the React namespace, which is expected not
// to exist when using React 17 and earlier, and that's fine.
const uSESKey = "useSyncExternalStore" as keyof typeof React;
const realHook = React[uSESKey] as RealUseSESHookType | undefined;

// Adapted from https://www.npmjs.com/package/use-sync-external-store, with
// Apollo Client deviations called out by "// DEVIATION ..." comments.

export const useSyncExternalStore: RealUseSESHookType = (
// When/if React.useSyncExternalStore is defined, delegate fully to it.
export const useSyncExternalStore: RealUseSESHookType = realHook || ((
subscribe,
getSnapshot,
getServerSnapshot,
) => {
// When/if React.useSyncExternalStore is defined, delegate fully to it.
const realHook = (React as {
useSyncExternalStore?: RealUseSESHookType;
}).useSyncExternalStore;
if (realHook) {
return realHook(subscribe, getSnapshot, getServerSnapshot);
}

// Read the current snapshot from the store on every render. Again, this
// breaks the rules of React, and only works here because of specific
// implementation details, most importantly that updates are
Expand Down Expand Up @@ -112,7 +111,7 @@ export const useSyncExternalStore: RealUseSESHookType = (
}, [subscribe]);

return value;
}
});

function checkIfSnapshotChanged<Snapshot>({
value,
Expand Down

0 comments on commit 06cf0b8

Please sign in to comment.