Sub topic 7
Context and State Still Flow Through Portals
What this chapter assumes
You should know createPortal, useContext, and useState. You should also know the difference between the React component tree and the DOM tree from earlier chapters. This chapter shows which behaviors follow each tree.
The rule
A portal changes where DOM nodes are placed. It does not change where a component sits in the React tree. Context, state, and unmounting all follow the React tree, so portal content behaves as a normal child of the component that renders it.
Context
A component inside a portal reads the nearest provider above it in the React tree. The DOM location is irrelevant. Here the panel is attached to document.body, but it still sees the "dark" value.
import { createContext, useContext } from 'react';
import { createPortal } from 'react-dom';
const ThemeContext = createContext('light');
function ThemedPanel({ children }) {
const theme = useContext(ThemeContext);
return createPortal(
<div className={`panel panel-${theme}`}>{children}</div>,
document.body
);
}
export default function App() {
return (
<ThemeContext.Provider value="dark">
<main>
<ThemedPanel>Hello</ThemedPanel>
</main>
</ThemeContext.Provider>
);
}This is why a modal can use your theme, router, or translation context without extra setup. You do not need to wrap the portal content in a second provider.
State
State belongs to the component that calls useState. Portal content is rendered by that component, so its handlers can close over the state and call the setter directly.
import { useState } from 'react';
import { createPortal } from 'react-dom';
function Counter() {
const [count, setCount] = useState(0);
return (
<section>
<p>Count: {count}</p>
{createPortal(
<button onClick={() => setCount((c) => c + 1)}>Add one</button>,
document.body
)}
</section>
);
}The button is outside the section in the DOM. Clicking it still updates the paragraph, because both belong to the same component instance.
Portal lifetime also follows the React tree. When the parent unmounts, the portal content unmounts and its DOM nodes are removed. When the parent re-renders, the portal content re-renders with it.
What follows which tree
| Behavior | Follows the React tree | Follows the DOM tree |
|---|---|---|
| Context values | Yes | No |
| State and props | Yes | No |
| Mount and unmount | Yes | No |
| Event bubbling to React handlers | Yes | No |
| CSS inheritance (`color`, `font-family`) | No | Yes |
| CSS selectors such as `.card .tooltip` | No | Yes |
| Layout, clipping, stacking | No | Yes |
Common errors
- Starting a second React root. If you call
createRooton the portal container and render into it, that content is a separate React tree. It does not see your providers or share your state. UsecreatePortalfrom inside the existing tree instead. - Expecting a DOM-based selector to match. A rule like
.sidebar .tooltipstops matching once the tooltip moves todocument.body. Give the portal content its own class. - Putting the provider inside the container. A provider that wraps only the portal's target node does nothing, because React reads providers from the component tree. Put providers above the component that creates the portal.
- Keeping state in the portal content when the parent may unmount it. Portal state disappears when the parent unmounts the portal. If it must survive, store it in a component above the one that conditionally renders the portal.
Exercise
A Toast component renders its message with createPortal(..., document.body). It calls useContext(LocaleContext) to choose a language. The app has <LocaleContext.Provider value="fr"> around the whole app. Which locale does the toast read, and why? Also, the toast text appears in the wrong font. What is the likely cause?
Show answer
It reads "fr". Context lookup follows the React tree, and the toast is still a descendant of the provider even though its DOM nodes are in document.body. The wrong font comes from CSS inheritance, which follows the DOM tree. The toast's DOM parent is document.body, so it no longer inherits the font set on the app's root element. Set the font on body, or on the toast's own class.