Context does persist through Portals even though the DOM tree may not align, the React component tree does align.
const TestContext = React.createContext();
function PortalChild() {
const context = useContext(TestContext);
return <p>{JSON.stringify(context)}</p>;
}
function PortalParent() {
const overlayContainer = useRef(document.createElement("div"));
useEffect(() => {
document.body.appendChild(overlayContainer.current);
}, []);
return ReactDOM.createPortal(<PortalChild />, overlayContainer.current);
}
export default function App() {
return (
<TestContext.Provider value={{ foo: "bar" }}>
<div className="App">
<PortalParent />
</div>
</TestContext.Provider>
);
}