From 27598b3ab60243edaabe8e60ede96032e7799ede Mon Sep 17 00:00:00 2001 From: Cody Bennett Date: Thu, 25 Apr 2024 12:08:09 -0500 Subject: [PATCH] experiment: polyfill concurrent readContext --- src/index.tsx | 25 +++++++++++++++---------- 1 file changed, 15 insertions(+), 10 deletions(-) diff --git a/src/index.tsx b/src/index.tsx index 3315d26..ed4f695 100644 --- a/src/index.tsx +++ b/src/index.tsx @@ -1,4 +1,4 @@ -import * as React from 'react' +import React from 'react' import type ReactReconciler from 'react-reconciler' /** @@ -75,15 +75,17 @@ function wrapContext(context: React.Context): React.Context { } } -const error = console.error -console.error = function () { - const message = [...arguments].join('') - if (message?.startsWith('Warning:') && message.includes('useContext')) { - console.error = error - return - } +const NO_CONTEXT = {} + +function readContextConcurrently(context: React.Context): T | typeof NO_CONTEXT { + // https://github.com/facebook/react/pull/28793 + const readContext = + (React as any).use ?? + (React as any).__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED?.ReactCurrentDispatcher?.current?.readContext - return error.apply(this, arguments as any) + if (typeof readContext === 'function') return readContext(wrapContext(context)) + + return NO_CONTEXT } const FiberContext = wrapContext(React.createContext(null!)) @@ -212,7 +214,10 @@ export function useContextMap(): ContextMap { const enableRenderableContext = node.type._context === undefined && node.type.Provider === node.type const context = enableRenderableContext ? node.type : node.type._context if (context && context !== FiberContext && !contextMap.has(context)) { - contextMap.set(context, React.useContext(wrapContext(context))) + const value = readContextConcurrently(context) + if (value === NO_CONTEXT) continue + + contextMap.set(context, value) } }