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

experiment: polyfill concurrent readContext #37

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
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
Loading