Skip to content

Commit

Permalink
Merge pull request #2025 from reduxjs/pr/lazyContext
Browse files Browse the repository at this point in the history
  • Loading branch information
markerikson committed Jun 13, 2023
2 parents a25d15c + aaf1364 commit 1812a78
Showing 1 changed file with 25 additions and 6 deletions.
31 changes: 25 additions & 6 deletions src/components/Context.ts
@@ -1,4 +1,5 @@
import { createContext } from 'react'
import type { Context } from 'react'
import type { Action, AnyAction, Store } from 'redux'
import type { Subscription } from '../utils/Subscription'
import { StabilityCheck } from '../hooks/useSelector'
Expand All @@ -13,13 +14,31 @@ export interface ReactReduxContextValue<
stabilityCheck: StabilityCheck
}

export const ReactReduxContext =
/*#__PURE__*/ createContext<ReactReduxContextValue>(null as any)
let realContext: Context<ReactReduxContextValue> | null = null
function getContext() {
if (!realContext) {
realContext = createContext<ReactReduxContextValue>(null as any)
if (process.env.NODE_ENV !== 'production') {
realContext.displayName = 'ReactRedux'
}
}
return realContext
}

export type ReactReduxContextInstance = typeof ReactReduxContext
export const ReactReduxContext = /*#__PURE__*/ new Proxy(
{} as Context<ReactReduxContextValue>,
/*#__PURE__*/ new Proxy<ProxyHandler<Context<ReactReduxContextValue>>>(
{},
{
get(_, handler) {
const target = getContext()
// @ts-ignore
return (_target, ...args) => Reflect[handler](target, ...args)
},
}
)
)

if (process.env.NODE_ENV !== 'production') {
ReactReduxContext.displayName = 'ReactRedux'
}
export type ReactReduxContextInstance = typeof ReactReduxContext

export default ReactReduxContext

0 comments on commit 1812a78

Please sign in to comment.