Skip to main content

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:

  • createPortal changes physical DOM placement without changing React ownership;
  • flushSync creates 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โ€‹

A portal changes placement, not ownershipContext and React event propagation follow the React tree even when DOM nodes are mounted somewhere else.
OWNERSHIPReact tree

App โ†’ Card โ†’ Modal โ†’ Dialog
Context flows through this path.
React events bubble through this path.

PLACEMENTDOM tree

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.

Portal lifecycle
1Parent renders portal
2React ownership stays with parent
3DOM mounts in target node
4Context + React events still use React ancestry

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.

A portal click reached an unexpected parent handler. What should you inspect first?
Portal React ancestryFind the logical React parent chain
Ancestor handlersCheck which React ancestors listen to the event
Interaction boundaryStop propagation only when the UX contract requires it
Ownership clarityMove the portal higher if ownership is conceptually wrong

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โ€‹

Default scheduling should remain the normal path
DEFAULTNormal React update

State update โ†’ React schedules/render work โ†’ commit when appropriate.
React keeps batching and prioritization freedom.

ESCAPE HATCHflushSync boundary

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.

Think in terms of DOM consistency, not setter execution
External system requires current DOM
React flushes work needed for consistency
DOM is ready for external read

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โ€‹

Should this update use flushSync?
Only React-owned UI?No โ€” keep normal scheduling
External system reads DOM immediately?Maybe โ€” verify it truly needs the updated DOM before return
Integration can be redesigned?Prefer redesign over synchronous flushing
Requirement is unavoidable and measured?Use one narrow flushSync boundary

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 flushSync to 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?

Summaryโ€‹

React DOM escape hatches
createPortal
Changes DOM placement ยท preserves React ownership ยท preserves Context ยท React events follow React ancestry.
flushSync
Forces a narrow synchronous commit boundary ยท justified by external DOM timing requirements ยท reduces scheduling flexibility.

Referencesโ€‹