Skip to content

Commit 27598b3

Browse files
experiment: polyfill concurrent readContext
1 parent 598b81f commit 27598b3

File tree

1 file changed

+15
-10
lines changed

1 file changed

+15
-10
lines changed

src/index.tsx

+15-10
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import * as React from 'react'
1+
import React from 'react'
22
import type ReactReconciler from 'react-reconciler'
33

44
/**
@@ -75,15 +75,17 @@ function wrapContext<T>(context: React.Context<T>): React.Context<T> {
7575
}
7676
}
7777

78-
const error = console.error
79-
console.error = function () {
80-
const message = [...arguments].join('')
81-
if (message?.startsWith('Warning:') && message.includes('useContext')) {
82-
console.error = error
83-
return
84-
}
78+
const NO_CONTEXT = {}
79+
80+
function readContextConcurrently<T>(context: React.Context<T>): T | typeof NO_CONTEXT {
81+
// https://github.com/facebook/react/pull/28793
82+
const readContext =
83+
(React as any).use ??
84+
(React as any).__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED?.ReactCurrentDispatcher?.current?.readContext
8585

86-
return error.apply(this, arguments as any)
86+
if (typeof readContext === 'function') return readContext(wrapContext(context))
87+
88+
return NO_CONTEXT
8789
}
8890

8991
const FiberContext = wrapContext(React.createContext<Fiber>(null!))
@@ -212,7 +214,10 @@ export function useContextMap(): ContextMap {
212214
const enableRenderableContext = node.type._context === undefined && node.type.Provider === node.type
213215
const context = enableRenderableContext ? node.type : node.type._context
214216
if (context && context !== FiberContext && !contextMap.has(context)) {
215-
contextMap.set(context, React.useContext(wrapContext(context)))
217+
const value = readContextConcurrently(context)
218+
if (value === NO_CONTEXT) continue
219+
220+
contextMap.set(context, value)
216221
}
217222
}
218223

0 commit comments

Comments
 (0)