Skip to content

Commit 1812a78

Browse files
authored
Merge pull request #2025 from reduxjs/pr/lazyContext
2 parents a25d15c + aaf1364 commit 1812a78

File tree

1 file changed

+25
-6
lines changed

1 file changed

+25
-6
lines changed

Diff for: src/components/Context.ts

+25-6
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { createContext } from 'react'
2+
import type { Context } from 'react'
23
import type { Action, AnyAction, Store } from 'redux'
34
import type { Subscription } from '../utils/Subscription'
45
import { StabilityCheck } from '../hooks/useSelector'
@@ -13,13 +14,31 @@ export interface ReactReduxContextValue<
1314
stabilityCheck: StabilityCheck
1415
}
1516

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

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

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

2544
export default ReactReduxContext

0 commit comments

Comments
 (0)