Skip to content

Commit

Permalink
experiment: polyfill concurrent readContext
Browse files Browse the repository at this point in the history
  • Loading branch information
CodyJasonBennett committed Apr 25, 2024
1 parent 598b81f commit 27598b3
Showing 1 changed file with 15 additions and 10 deletions.
25 changes: 15 additions & 10 deletions src/index.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import * as React from 'react'
import React from 'react'
import type ReactReconciler from 'react-reconciler'

/**
Expand Down Expand Up @@ -75,15 +75,17 @@ function wrapContext<T>(context: React.Context<T>): React.Context<T> {
}
}

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<T>(context: React.Context<T>): 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<Fiber>(null!))
Expand Down Expand Up @@ -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)
}
}

Expand Down

0 comments on commit 27598b3

Please sign in to comment.