Sub topic 7
Context and state still flow through portals
This chapter assumes you know useState, useContext and createContext, and that you have used createPortal to move a modal to document.body. It builds on the previous chapter, where events bubbled through the React tree rather than the DOM tree. Context and state follow the same rule.
The rule: ownership follows the React tree
createPortal changes where React puts DOM nodes. It does not change where the portal's children sit in the component tree. The portal element is still a child of the component that rendered it. So everything React attaches to tree position keeps working:
- Context values from
Providerancestors. - State and props from the component that renders the portal.
- Error boundaries above the portal.
- Synthetic event bubbling, covered in the previous chapter.
Everything the browser attaches to DOM position does not carry over:
- CSS inheritance and descendant selectors.
- Native event bubbling (a native listener on the original parent never fires).
- Layout, clipping and stacking behavior.
Keeping these two groups apart explains most portal bugs.
Context reaches portal content
A context consumer looks upward through the React tree for the nearest provider. A portal child's nearest provider is the one above the component that rendered the portal, wherever the DOM nodes ended up.
import { createContext, useContext, useState } from 'react';
import { createPortal } from 'react-dom';
const ThemeContext = createContext('light');
function ThemeBadge() {
const theme = useContext(ThemeContext);
return <p>Current theme: {theme}</p>;
}
function Modal({ children, onClose }) {
return createPortal(
<div className="backdrop" onClick={onClose}>
<div
className="dialog"
role="dialog"
aria-modal="true"
onClick={(e) => e.stopPropagation()}
>
{children}
<button onClick={onClose}>Close</button>
</div>
</div>,
document.body
);
}
export default function App() {
const [theme, setTheme] = useState('dark');
const [open, setOpen] = useState(false);
return (
<ThemeContext.Provider value={theme}>
<button onClick={() => setTheme(theme === 'dark' ? 'light' : 'dark')}>
Toggle theme
</button>
<button onClick={() => setOpen(true)}>Open modal</button>
{open && (
<Modal onClose={() => setOpen(false)}>
<ThemeBadge />
</Modal>
)}
</ThemeContext.Provider>
);
}ThemeBadge renders under document.body, yet it shows "dark". With the modal open, click "Toggle theme". The badge text changes, because the provider's value changed and React re-renders every consumer below it, portal or not.
Modal has no theme prop and no import of the provider. It does not need either, so portal components can stay as generic as ordinary ones.
State belongs to whoever renders it
A portal has no state of its own. State lives in the component that calls useState. Two placements are common.
State in the parent, passed down. In the example above, open lives in App. The modal reads it through the {open && ...} condition and writes it through onClose. This is the usual choice when the trigger and the dialog must agree on something.
State inside the portal content. A form inside the modal can keep its own draft:
import { useState } from 'react';
function RenameForm({ initialName, onSave }) {
const [draft, setDraft] = useState(initialName);
return (
<form
onSubmit={(e) => {
e.preventDefault();
onSave(draft);
}}
>
<label>
Name
<input value={draft} onChange={(e) => setDraft(e.target.value)} />
</label>
<button type="submit">Save</button>
</form>
);
}Placed inside <Modal>, RenameForm keeps draft while the modal stays mounted. When {open && ...} becomes false, React unmounts the portal and its children, and the draft is lost. That is often what you want, because the form starts fresh next time. If you need the draft to survive closing, you have two options:
- Lift
draftto a component that stays mounted. - Keep the modal mounted and hide it. For example, render
nullfor the dialog contents but keep the state-holding component outside the conditional.
When the container changes
React identifies a portal by its position in the tree and by its container node. If the container argument changes between renders, React treats the old portal and the new one as different things. It unmounts the children from the old container and mounts fresh ones in the new one, so their state resets. Pick the container once and keep it stable. Looking it up inside render with document.getElementById on every render is safe only when the lookup returns the same node each time.
Several levels of portals
Portals can nest. A tooltip inside a modal can be its own portal, and context from the app root reaches both. The tooltip's DOM node sits in document.body next to the modal, not inside it. As the previous chapter showed, a click in the tooltip still bubbles through the modal's React handlers. A handler on the modal's backdrop will see clicks from the tooltip. That is why the modal in this chapter stops propagation on the dialog box.
What does not flow: CSS
A common surprise follows from the DOM/React split. Suppose the app applies a theme with a class on a wrapper:
function Page({ theme, children }) {
return <div className={`page page-${theme}`}>{children}</div>;
}and your stylesheet has:
.page-dark .dialog {
background: #222;
color: #eee;
}The dialog is not inside .page-dark in the DOM, so the selector never matches. Color, font and CSS custom properties set on .page-dark are also not inherited. There are two reliable fixes.
Read the theme from context and apply it to the portal's own root:
import { createContext, useContext } from 'react';
import { createPortal } from 'react-dom';
const ThemeContext = createContext('light');
function ThemedPortal({ children }) {
const theme = useContext(ThemeContext);
return createPortal(
<div className={`portal-root page-${theme}`}>{children}</div>,
document.body
);
}Put theme variables on :root or body (for example through a data-theme attribute on document.documentElement), so every part of the DOM sees them. This is the better choice when theming is global.
Use context when the value is data. Use a global CSS hook when the value is purely visual.
Where context is lost: a second React root
This is the one case where "portal content keeps context" is false, and it fails because no portal is involved. If you create a separate root with createRoot and render into a node outside your app, that root is a separate React tree with no providers above it:
import { useContext, useEffect } from 'react';
import { createRoot } from 'react-dom/client';
function mountWidget(node) {
const root = createRoot(node);
root.render(<ThemeBadge />); // useContext(ThemeContext) returns 'light', the default
return root;
}
function WidgetHost() {
useEffect(() => {
const node = document.createElement('div');
document.body.appendChild(node);
const root = mountWidget(node);
return () => {
root.unmount();
node.remove();
};
}, []);
return null;
}Here ThemeBadge always sees the default value, because no provider wraps the new root. State is also disconnected: you must pass data in explicitly by calling root.render again with new props. Developers who mix imperative libraries (a map, a chart, a legacy widget) with React hit this often. If the code is yours, replace the second root with a portal and the problem disappears. If you must keep a second root, wrap its content in the providers it needs:
root.render(
<ThemeContext.Provider value={theme}>
<ThemeBadge />
</ThemeContext.Provider>
);You then have to re-render it whenever theme changes. This is why a portal is the better default.
Errors and Suspense
Error boundaries are tree features, so they work across portals. If a component inside a modal throws during render, the nearest error boundary above the portal call catches it, not one in the DOM parent. Place a boundary inside the portal content if you want a crash in the dialog to show a message inside the dialog and keep the page alive. The same applies to Suspense: a suspended component inside a portal shows the fallback of the nearest Suspense ancestor in the React tree. That fallback may render outside the dialog, so add a Suspense boundary inside the portal when you want a loading state in the dialog itself.
Common mistakes
| Symptom | Cause | Fix |
|---|---|---|
| Portal content shows default context values | Content was rendered with a separate `createRoot` | Use `createPortal`, or wrap the second root in the same providers |
| Dialog ignores a `.theme-dark .dialog` rule | CSS selector depends on DOM ancestry | Apply the class to the portal root from context, or use variables on `:root` |
| Form text vanishes each time the modal opens | Modal unmounts on close, so its state resets | Lift the state, or keep the state holder mounted |
| State resets when the container changes | Different container means a different portal | Keep the container node stable |
| Parent handler fires for clicks in the portal | Synthetic events bubble through the React tree | Stop propagation at the portal root, or check `event.target` |
Summary of what you can rely on
Context and state follow the component tree, so a portal can use the app's providers, state and error boundaries without extra wiring. CSS and native DOM behavior follow the DOM tree, so portal content needs explicit styling hooks. A separate React root is the exception that loses context entirely.
Exercise
A Tooltip component renders its bubble with createPortal(..., document.body). Inside the bubble, a <UserName /> component calls useContext(UserContext), and UserContext.Provider wraps App. A teammate says the tooltip must receive user as a prop because it is outside the app's DOM. Is the teammate right? What would change if the tooltip were mounted with a separate createRoot call instead?
Show answer
The teammate is wrong. UserName is still a descendant of UserContext.Provider in the React tree, so useContext returns the provided value, even though its DOM node is under document.body. With a separate createRoot, the tooltip would be a different React tree with no provider above it. useContext would return the default value, so the provider (or the data as props) would have to be supplied to that root explicitly.
Exercise
A modal rendered through a portal contains <input> for a draft message. The parent renders {open && <Modal>...</Modal>}. Users complain that closing and reopening the modal clears their draft. Give two ways to keep the draft, and say why the draft is lost in the current code.
Show answer
The draft is lost because open becoming false unmounts the portal and its children, which destroys the input component's state. To keep it, either lift the draft state into a component that stays mounted (for example the parent) and pass value and onChange down, or keep the component that holds the state mounted and only hide or skip rendering the dialog markup.
Exercise
Your stylesheet contains .app-dark .dialog { background: #222; }. The .app-dark class is on the root wrapper, and the dialog is rendered through a portal into document.body. The dialog stays light. Why, and how can you fix it without changing the stylesheet's meaning?
Show answer
CSS selectors match DOM ancestry, and the dialog's DOM node is not inside .app-dark, since it is a child of document.body. Fix it by reading the theme from context inside the portal component and adding the app-dark class (or an equivalent) to the portal's own root element, or by moving the theme hook to document.documentElement so it applies to everything.