Skip to content

Commit 51cfc4c

Browse files
phryneasmarkerikson
authored andcommitted
lazily create Context for RSC compat
1 parent 6007055 commit 51cfc4c

File tree

1 file changed

+25
-7
lines changed

1 file changed

+25
-7
lines changed

src/components/Context.ts

+25-7
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { createContext } from 'react'
1+
import { Context, createContext } from 'react'
22
import type { Action, AnyAction, Store } from 'redux'
33
import type { Subscription } from '../utils/Subscription'
44
import { StabilityCheck } from '../hooks/useSelector'
@@ -13,13 +13,31 @@ export interface ReactReduxContextValue<
1313
stabilityCheck: StabilityCheck
1414
}
1515

16-
export const ReactReduxContext =
17-
/*#__PURE__*/ createContext<ReactReduxContextValue>(null as any)
16+
let realContext: Context<ReactReduxContextValue> | null = null
17+
function getContext() {
18+
if (!realContext) {
19+
realContext = createContext<ReactReduxContextValue>(null as any)
20+
if (process.env.NODE_ENV !== 'production') {
21+
realContext.displayName = 'ReactRedux'
22+
}
23+
}
24+
return realContext
25+
}
1826

19-
export type ReactReduxContextInstance = typeof ReactReduxContext
27+
export const ReactReduxContext = /*#__PURE__*/ new Proxy(
28+
{} as Context<ReactReduxContextValue>,
29+
new Proxy<ProxyHandler<Context<ReactReduxContextValue>>>(
30+
{},
31+
{
32+
get(_, handler) {
33+
const target = getContext()
34+
// @ts-ignore
35+
return (_target, ...args) => Reflect[handler](target, ...args)
36+
},
37+
}
38+
)
39+
)
2040

21-
if (process.env.NODE_ENV !== 'production') {
22-
ReactReduxContext.displayName = 'ReactRedux'
23-
}
41+
export type ReactReduxContextInstance = typeof ReactReduxContext
2442

2543
export default ReactReduxContext

0 commit comments

Comments
 (0)