Skip to content

Commit

Permalink
lazily create Context for RSC compat
Browse files Browse the repository at this point in the history
  • Loading branch information
phryneas committed Jun 5, 2023
1 parent ee7ac84 commit fa4e3ce
Showing 1 changed file with 25 additions and 7 deletions.
32 changes: 25 additions & 7 deletions src/components/Context.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { createContext } from 'react'
import { Context, createContext } from 'react'
import type { Action, AnyAction, Store } from 'redux'
import type { Subscription } from '../utils/Subscription'

Expand All @@ -11,13 +11,31 @@ export interface ReactReduxContextValue<
getServerState?: () => SS
}

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>,
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 fa4e3ce

Please sign in to comment.