Skip to content

Commit

Permalink
Map React.Context instances by React.createContext (#11026)
Browse files Browse the repository at this point in the history
* Map React.Context instances by React.createContext
  • Loading branch information
phryneas authored Jul 6, 2023
1 parent 788262d commit b8d405e
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 13 deletions.
6 changes: 6 additions & 0 deletions .changeset/itchy-bulldogs-help.md
Original file line number Diff line number Diff line change
@@ -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`.
4 changes: 2 additions & 2 deletions .size-limit.cjs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
const checks = [
{
path: "dist/apollo-client.min.cjs",
limit: "37915"
limit: "37976"
},
{
path: "dist/main.cjs",
Expand All @@ -10,7 +10,7 @@ const checks = [
{
path: "dist/index.js",
import: "{ ApolloClient, InMemoryCache, HttpLink }",
limit: "33413"
limit: "33437"
},
...[
"ApolloProvider",
Expand Down
26 changes: 15 additions & 11 deletions src/react/context/ApolloContext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,12 @@ export interface ApolloContextValue {
suspenseCache?: SuspenseCache;
}

type ReactVersion = string;
declare global {
interface Window {
[contextKey]: Record<ReactVersion, React.Context<ApolloContextValue>>;
[contextKey]: Map<
typeof React.createContext,
React.Context<ApolloContextValue>
>;
}
}

Expand All @@ -40,16 +42,18 @@ export function getApolloContext(): React.Context<ApolloContextValue> {
'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<ApolloContextValue>({}),
{ displayName: 'ApolloContext' },
)
);
let value = contextStorage.get(React.createContext);
if (!value) {
value = Object.assign(React.createContext<ApolloContextValue>({}), {
displayName: 'ApolloContext',
});
contextStorage.set(React.createContext, value);
}

return value;
}

/**
Expand Down

0 comments on commit b8d405e

Please sign in to comment.