Skip to content

Instantly share code, notes, and snippets.

@hyrious
Created April 16, 2025 09:27
Show Gist options
  • Save hyrious/17ba115114fc8873fc88d45353a84342 to your computer and use it in GitHub Desktop.
Save hyrious/17ba115114fc8873fc88d45353a84342 to your computer and use it in GitHub Desktop.
Skip possible nested context when passing React children.
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