Created
April 16, 2025 09:27
-
-
Save hyrious/17ba115114fc8873fc88d45353a84342 to your computer and use it in GitHub Desktop.
Skip possible nested context when passing React children.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { createContext, use, useState } from 'react'; | |
import { createPortal } from 'react-dom'; | |
import { createRoot } from 'react-dom/client'; | |
const Context = createContext<string>('') | |
function Test() { | |
const theme = use(Context) | |
return <div>"{theme}"</div> | |
} | |
interface Props { | |
children?: React.ReactNode; | |
} | |
function NestedService(props: Props) { | |
return ( | |
<Context.Provider value='nested'> | |
{props.children} | |
</Context.Provider> | |
) | |
} | |
function App() { | |
const [dom, setDOM] = useState<HTMLElement | null>(null) | |
const widget = <Test /> | |
// Notice how this code does NOT know anything about contexts outside and inside. | |
return <> | |
<NestedService> | |
<div ref={setDOM} /> | |
</NestedService> | |
{dom && createPortal(widget, dom)} | |
</> | |
} | |
createRoot(document.querySelector('#app')!).render( | |
<Context.Provider value='app'> | |
<App /> | |
</Context.Provider> | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment