Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

lazily create Context for RSC compat #2025

Merged
merged 3 commits into from
Jun 13, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 25 additions & 6 deletions src/components/Context.ts
Original file line number Diff line number Diff line change
@@ -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