Portals, flushSync, and React DOM escape hatches
Most React code should let React choose where work is scheduled and let the normal component tree decide who owns UI.
Two React DOM APIs intentionally cross those defaults:
createPortalchanges physical DOM placement without changing React ownership;flushSynccreates a narrow synchronous commit boundary for an external integration that needs the DOM updated before control returns.
React ownership and DOM placement are different treesโ
App โ Card โ Modal โ Dialog
Context flows through this path.
React events bubble through this path.
body โ #root โ card DOM
body โ portal target โ dialog DOM
CSS stacking and overflow depend on this tree.
That distinction is the entire portal mental model.
createPortalโ
import { createPortal } from 'react-dom';
function Modal({ children }) {
return createPortal(
<div className="modal-layer">{children}</div>,
document.body
);
}
createPortal(children, domNode, key?) returns a React node. The target DOM node must already exist.
Why portals existโ
A modal rendered inside a clipped card can be visually trapped by overflow or stacking contexts.
<div className="card">
<Toolbar />
<Modal />
</div>
A portal lets the modal remain conceptually owned by Card while placing the actual dialog DOM near document.body.
Context still worksโ
const ThemeContext = createContext('light');
function App() {
return (
<ThemeContext value="dark">
<Page />
</ThemeContext>
);
}
function Modal() {
const theme = useContext(ThemeContext);
return createPortal(
<div data-theme={theme}>Dialog</div>,
document.body
);
}
The dialog can read the provider above Page because Context follows the React tree, not physical DOM ancestry.
React events also follow React ownershipโ
function Panel() {
return (
<div onClick={() => console.log('panel clicked')}>
{createPortal(<button>Open</button>, document.body)}
</div>
);
}
Clicking the portal button can reach the React onClick on Panel even though the button is not inside that div in the DOM.
Portals are only placement infrastructureโ
A production modal still needs accessible behavior:
- dialog semantics and an accessible name;
- focus movement into the dialog;
- focus restoration on close;
- Escape-key handling;
- background interaction management;
- scroll-locking where appropriate.
function Modal({ title, onClose, children }) {
return createPortal(
<div className="backdrop" onMouseDown={onClose}>
<section
role="dialog"
aria-modal="true"
aria-labelledby="dialog-title"
onMouseDown={event => event.stopPropagation()}
>
<h2 id="dialog-title">{title}</h2>
{children}
</section>
</div>,
document.body
);
}
Integrating with non-React DOMโ
Portals can also project React content into a DOM container supplied by another system:
function MapPopup({ container, children }) {
if (!container) return null;
return createPortal(children, container);
}
Useful examples include map popups, CMS slots, legacy shells, and embedded widgets.
If the target DOM node changes, React recreates the portal content in the new location. Prefer stable targets unless moving the subtree is intentional.
flushSync
flushSync tells React that an external boundary requires the DOM to reflect an update synchronously.
import { flushSync } from 'react-dom';
flushSync(() => {
setIsPrinting(true);
});
// Required DOM update has committed by here.
Normal scheduling vs synchronous integrationโ
State update โ React schedules/render work โ commit when appropriate.
React keeps batching and prioritization freedom.
External callback โ flushSync update โ required DOM commits now โ external system reads DOM.
Scheduling flexibility is reduced.
If everything involved is React-owned, you usually do not need flushSync.
Real use case: browser integrationโ
useEffect(() => {
function handleBeforePrint() {
flushSync(() => {
setIsPrinting(true);
});
}
function handleAfterPrint() {
setIsPrinting(false);
}
window.addEventListener('beforeprint', handleBeforePrint);
window.addEventListener('afterprint', handleAfterPrint);
return () => {
window.removeEventListener('beforeprint', handleBeforePrint);
window.removeEventListener('afterprint', handleAfterPrint);
};
}, []);
The browser's print lifecycle may require the updated document layout before the callback finishes. That is an external timing contract, not a normal state-update pattern.
flushSync is broader than one setterโ
React may need to flush other pending work to satisfy the synchronous boundary. It can also cause pending Effects or Suspense behavior to become observable sooner than expected.
What flushSync does not solveโ
It does not change state snapshot or closure semantics:
setCount(c => c + 1);
Use a functional updater for stale-state dependencies rather than forcing synchronous commits.
It is also not a performance optimization. Frequent synchronous flushing can block the main thread and remove React's scheduling flexibility.
Decision ruleโ
Common mistakesโ
- assuming portal children lose Context;
- reasoning about portal events only from DOM ancestry;
- using portals as a substitute for clear ownership;
- forcing every update through
flushSync; - using
flushSyncto work around stale closures; - treating synchronous commits as a performance shortcut.
Exerciseโ
Build a global confirmation dialog that renders into document.body, inherits theme Context, handles backdrop clicks correctly, restores focus, and never uses flushSync.
Then add a separate print-preview integration where the browser genuinely requires a DOM update before printing and justify one narrow flushSync call.
Interview questionsโ
Junior: What does createPortal change, and what does it preserve?
Mid-level: Why can a portal click reach a React ancestor that is not its DOM ancestor?
Senior: What external timing requirement would justify flushSync, and what scheduling/performance trade-off does it introduce?