From b8d405eee2a81df92861be5abd9bd874d7cad111 Mon Sep 17 00:00:00 2001 From: Lenz Weber-Tronic Date: Thu, 6 Jul 2023 11:47:14 +0200 Subject: [PATCH] Map React.Context instances by React.createContext (#11026) * Map React.Context instances by React.createContext --- .changeset/itchy-bulldogs-help.md | 6 ++++++ .size-limit.cjs | 4 ++-- src/react/context/ApolloContext.ts | 26 +++++++++++++++----------- 3 files changed, 23 insertions(+), 13 deletions(-) create mode 100644 .changeset/itchy-bulldogs-help.md diff --git a/.changeset/itchy-bulldogs-help.md b/.changeset/itchy-bulldogs-help.md new file mode 100644 index 00000000000..beb5bf7ec55 --- /dev/null +++ b/.changeset/itchy-bulldogs-help.md @@ -0,0 +1,6 @@ +--- +'@apollo/client': patch +--- + +Store React.Context instance mapped by React.createContext instance, not React.version. +Using `React.version` can cause problems with `preact`, as multiple versions of `preact` will all identify themselves as React `17.0.2`. diff --git a/.size-limit.cjs b/.size-limit.cjs index c9c78069eb9..44c7645900e 100644 --- a/.size-limit.cjs +++ b/.size-limit.cjs @@ -1,7 +1,7 @@ const checks = [ { path: "dist/apollo-client.min.cjs", - limit: "37915" + limit: "37976" }, { path: "dist/main.cjs", @@ -10,7 +10,7 @@ const checks = [ { path: "dist/index.js", import: "{ ApolloClient, InMemoryCache, HttpLink }", - limit: "33413" + limit: "33437" }, ...[ "ApolloProvider", diff --git a/src/react/context/ApolloContext.ts b/src/react/context/ApolloContext.ts index 8d1b4c8c424..a93c2709279 100644 --- a/src/react/context/ApolloContext.ts +++ b/src/react/context/ApolloContext.ts @@ -11,10 +11,12 @@ export interface ApolloContextValue { suspenseCache?: SuspenseCache; } -type ReactVersion = string; declare global { interface Window { - [contextKey]: Record>; + [contextKey]: Map< + typeof React.createContext, + React.Context + >; } } @@ -40,16 +42,18 @@ export function getApolloContext(): React.Context { 'For more information, see https://nextjs.org/docs/getting-started/react-essentials#client-components' ); - let contextStorage = global[contextKey] || ( - global[contextKey] = Object.create(null) - ); + let contextStorage = + global[contextKey] || (global[contextKey] = new Map()); - return contextStorage[React.version] || ( - contextStorage[React.version] = Object.assign( - React.createContext({}), - { displayName: 'ApolloContext' }, - ) - ); + let value = contextStorage.get(React.createContext); + if (!value) { + value = Object.assign(React.createContext({}), { + displayName: 'ApolloContext', + }); + contextStorage.set(React.createContext, value); + } + + return value; } /**