From fa4e3ce09448399c502a559847279c18957b9f6b Mon Sep 17 00:00:00 2001 From: Lenz Weber-Tronic Date: Mon, 5 Jun 2023 22:52:44 +0200 Subject: [PATCH] lazily create Context for RSC compat --- src/components/Context.ts | 32 +++++++++++++++++++++++++------- 1 file changed, 25 insertions(+), 7 deletions(-) diff --git a/src/components/Context.ts b/src/components/Context.ts index 821ca6af3..74969e67a 100644 --- a/src/components/Context.ts +++ b/src/components/Context.ts @@ -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' @@ -11,13 +11,31 @@ export interface ReactReduxContextValue< getServerState?: () => SS } -export const ReactReduxContext = - /*#__PURE__*/ createContext(null as any) +let realContext: Context | null = null +function getContext() { + if (!realContext) { + realContext = createContext(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, + new Proxy>>( + {}, + { + 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