Portals and Profiler

Render outside the parent's DOM, and measure renders.

Builds on Events.

Two small APIs close out the fundamentals. Both are about the edges of React's model. A portal lets a component render DOM somewhere other than inside its parent's DOM node, which modals, tooltips and toasts need. A <Profiler> measures how long a part of the tree takes to render, from code.

They're unrelated except for one thing: each is easy to use and has one behavior people don't expect. For portals, it's how events bubble. For the Profiler, it's that it does nothing in a normal production build.

The problem: a popover trapped in its card#

Cards often use overflow: hidden for rounded corners or truncated text. Put a popover inside one and it gets clipped. Hover both triggers below.

Clipped by an ancestor, then escaped with a portal
import { useLayoutEffect, useRef, useState, type ReactNode } from "react";
import { createPortal } from "react-dom";

const tipStyle = { background: "#292524", color: "white", padding: "6px 10px", borderRadius: 6, fontSize: 13, width: 200 } as const;

function InlineTip({ text, children }: { text: string; children: ReactNode }) {
  const [show, setShow] = useState(false);
  return (
    <span style={{ position: "relative" }} onMouseEnter={() => setShow(true)} onMouseLeave={() => setShow(false)}>
      {children}
      {show ? <span style={{ ...tipStyle, position: "absolute", top: "120%", left: 0 }}>{text}</span> : null}
    </span>
  );
}

function PortalTip({ text, children }: { text: string; children: ReactNode }) {
  const [show, setShow] = useState(false);
  const [pos, setPos] = useState({ top: 0, left: 0 });
  const triggerRef = useRef<HTMLSpanElement>(null);

  // Measure before paint so the tooltip never flashes in the wrong place.
  useLayoutEffect(() => {
    if (!show || !triggerRef.current) return;
    const r = triggerRef.current.getBoundingClientRect();
    setPos({ top: r.bottom + 6, left: r.left });
  }, [show]);

  return (
    <span ref={triggerRef} onMouseEnter={() => setShow(true)} onMouseLeave={() => setShow(false)}>
      {children}
      {show ? createPortal(<span role="tooltip" style={{ ...tipStyle, position: "fixed", ...pos }}>{text}</span>, document.body) : null}
    </span>
  );
}

const card = { overflow: "hidden", border: "1px solid #d6d3d1", borderRadius: 10, padding: 12, height: 56, marginBottom: 12 } as const;

export default function App() {
  return (
    <div style={{ paddingBottom: 80 }}>
      <div style={card}>
        <InlineTip text="Published 1999. Martin Fowler's catalog of refactorings.">
          <u>Refactoring</u> (inline tooltip)
        </InlineTip>
      </div>
      <div style={card}>
        <PortalTip text="Published 2021. Build two interpreters from scratch.">
          <u>Crafting Interpreters</u> (portal tooltip)
        </PortalTip>
      </div>
    </div>
  );
}

The inline tooltip is cut off at the card's edge. No z-index can fix it: overflow: hidden clips descendants no matter what, and a parent with transform, filter or its own z-index creates a stacking context its children can't climb out of. The only real escape is to put the tooltip's DOM somewhere else, usually directly in document.body. That's what the second one does.

createPortal#

createPortal(children, domNode, key?) comes from react-dom. It returns something you render like any other element, and React mounts children into domNode instead of into the parent's DOM node.

import { createPortal } from "react-dom";

function Toast({ message }: { message: string }) {
  return createPortal(<div className="toast">{message}</div>, document.body);
}

Only the DOM placement changes. In every other way the portal's content is still a normal child of the component that rendered it:

  • It reads context from its React parents, so a modal still sees your theme and your router.
  • Its state belongs to the component tree where you rendered it, and it unmounts with that component.
  • Events bubble through the React tree, not the DOM tree. This is the surprising one.
Portals: React tree versus DOM tree
React treeAppCardonClickcreatePortalbutton LikeDOM treediv.carddiv#rootbuttondiv.modalbody
Step 1 of 4

In the React tree, the modal is a child of Card: Card rendered it. In the DOM, createPortal put its nodes under document.body, nowhere near the card's div.

Seeing the bubbling#

Here a card has both a React onClick and a plain DOM listener added with addEventListener. Its modal is portaled to body. Click the button inside the modal and compare the console with clicking the card itself.

React events bubble through portals
import { useEffect, useRef, useState } from "react";
import { createPortal } from "react-dom";

export default function App() {
  const [open, setOpen] = useState(true);
  const cardRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const card = cardRef.current!;
    const native = () => console.log("native listener on div.card");
    card.addEventListener("click", native);
    return () => card.removeEventListener("click", native);
  }, []);

  return (
    <div ref={cardRef} onClick={() => console.log("React onClick on Card")} style={{ border: "1px solid #d6d3d1", padding: 12, borderRadius: 8 }}>
      <strong>Refactoring</strong> (click the card) <button onClick={() => setOpen((o) => !o)}>{open ? "Hide" : "Show"} modal</button>
      {open
        ? createPortal(
            <div style={{ position: "fixed", right: 12, bottom: 12, background: "white", border: "1px solid #b4532a", borderRadius: 8, padding: 12 }}>
              Modal content, rendered into body.{" "}
              <button onClick={() => console.log("button inside the portal")}>Click me</button>
            </div>,
            document.body,
          )
        : null}
    </div>
  );
}
Nothing logged yet.

Clicking "Click me" logs the button, then React onClick on Card, but never the native listener. In the DOM the button isn't inside the card, so the browser's own bubbling never reaches div.card. React, though, dispatches its synthetic events along the component tree, and in that tree the button is the card's descendant.

This is deliberate. It makes a portal behave like any other child, so a parent that wraps a dropdown can still handle events from it. But it bites in two common places:

  • A clickable parent (a card or a table row that navigates on click) also receives clicks from inside the modal it opened.
  • "Click outside to close" code that checks rootRef.current.contains(event.target) with DOM APIs thinks a click inside the portaled menu was outside, because in the DOM it was.

The fixes: stop propagation at the portal's root (onClick={(e) => e.stopPropagation()}), render the modal from a component that isn't inside the clickable parent, or, for outside clicks, use React's tree (an onClick on the portal content that marks the click as inside) instead of DOM containment.

PredictWhich listeners fire?

A div has onClickCapture={() => log("capture")} and onClick={() => log("bubble")}. Inside it, a component renders createPortal(<button onClick={() => log("button")}>Go</button>, document.body). The user clicks Go. What's logged, in order?

Modals: what a portal doesn't do for you#

A portal solves placement. It doesn't make a modal accessible. A real modal dialog needs:

  • Semantics. role="dialog" and aria-modal="true" on the container, and a name via aria-labelledby pointing at its title.
  • Focus moves in. When it opens, focus goes into the dialog, to the first field or the dialog itself, so keyboard and screen reader users land in it.
  • Focus stays in. Tab shouldn't wander into the page behind. The modern way is to make the rest of the page inert, which removes it from the tab order and from assistive technology (React 19 supports the inert attribute as a boolean).
  • Escape closes it.
  • Focus goes back. On close, focus returns to the element that opened it, or keyboard users are dumped at the top of the page.
  • Scroll lock on the page behind, usually.
An accessible modal on a portal
import { useEffect, useEffectEvent, useId, useRef, type ReactNode } from "react";
import { createPortal } from "react-dom";

export function Modal({ title, onClose, children }: { title: string; onClose: () => void; children: ReactNode }) {
  const titleId = useId();
  const dialogRef = useRef<HTMLDivElement>(null);
  const onEscape = useEffectEvent(() => onClose()); // always the latest onClose

  useEffect(() => {
    const opener = document.activeElement as HTMLElement | null;
    dialogRef.current?.focus(); // focus moves in
    const onKey = (e: KeyboardEvent) => {
      if (e.key === "Escape") onEscape();
    };
    document.addEventListener("keydown", onKey);
    return () => {
      document.removeEventListener("keydown", onKey);
      opener?.focus(); // focus goes back
    };
  }, []);

  return createPortal(
    <div style={{ position: "fixed", inset: 0, background: "rgba(41,37,36,0.35)", display: "grid", placeItems: "center" }}>
      <div
        ref={dialogRef}
        role="dialog"
        aria-modal="true"
        aria-labelledby={titleId}
        tabIndex={-1}
        style={{ background: "white", borderRadius: 10, padding: 16, width: 280 }}
      >
        <h3 id={titleId} style={{ marginTop: 0 }}>{title}</h3>
        {children}
        <button onClick={onClose}>Close</button>
      </div>
    </div>,
    document.body,
  );
}

Open it with the keyboard (Tab to the button, press Enter), press Tab a few times, then Escape: focus never reaches the inert page behind, and it lands back on the button when the dialog closes. (Tab can still leave the document for the browser's own UI, which a real dialog allows too.) The useEffectEvent (from the effects chapter) lets the effect run once per open while still calling the latest onClose; with onClose as a dependency, an inline arrow from the parent would re-run the effect, and its focus restore, on every parent render.

Fix itLiking a book shouldn't select it

Clicking a card selects it. The Details button opens a modal (on a portal) with a Like button. But liking a book, or closing the modal, also selects the card. Fix it so clicks inside the modal never reach the card's onClick. Press Check.

Clicks escaping a portal
import type { ReactNode } from "react";
import { createPortal } from "react-dom";

export function Modal({ children }: { children: ReactNode }) {
  return createPortal(
    <div role="dialog" aria-modal="true" aria-label="Book details" style={{ position: "fixed", right: 12, bottom: 12, background: "white", border: "1px solid #b4532a", borderRadius: 8, padding: 12 }}>
      {children}
    </div>,
    document.body,
  );
}

Measuring renders with Profiler#

Sometimes you want render timings from code: to log how long a screen takes in a real session, to check a fix in a test, or to compare two implementations. <Profiler> wraps a part of the tree and calls onRender every time that part commits.

<Profiler id="BookList" onRender={onRender}>
  <BookList />
</Profiler>

onRender receives six arguments:

ArgumentMeaning
idThe id prop, so one callback can serve several Profilers.
phase"mount", "update", or "nested-update" (an update scheduled during a commit, for example by a layout effect, which React renders synchronously right after).
actualDurationMilliseconds spent rendering this Profiler's subtree for this commit. Components that skipped rendering (memoized, or not affected by the update) cost nothing here.
baseDurationEstimated milliseconds to re-render the whole subtree without any skipping: the sum of each component's most recent render time. The worst case.
startTimeWhen React started rendering this update (a performance.now() timestamp).
commitTimeWhen React committed this update. Shared by every Profiler in the same commit, so you can group them.

The gap between actualDuration and baseDuration tells you how much skipping saved. Below, the list is wrapped in memo, which skips re-rendering a component when its props haven't changed (memoization covers it properly). Each row burns 3ms with slowDown to stand in for a heavy component.

Profiler onRender arguments
import { memo, Profiler, useState, type ProfilerOnRenderCallback } from "react";
import { books, Rendered, slowDown } from "guide-tools";

const onRender: ProfilerOnRenderCallback = (id, phase, actualDuration, baseDuration, startTime, commitTime) => {
  console.log(
    `${id} ${phase}: actual ${actualDuration.toFixed(1)}ms, base ${baseDuration.toFixed(1)}ms, ` +
      `start ${startTime.toFixed(0)}, commit ${commitTime.toFixed(0)}`,
  );
};

function Row({ title }: { title: string }) {
  slowDown(3); // pretend this row is expensive
  return <li>{title}</li>;
}

const BookList = memo(function BookList({ items }: { items: typeof books }) {
  return (
    <Rendered label="BookList">
      <ul>{items.map((b) => <Row key={b.id} title={b.title} />)}</ul>
    </Rendered>
  );
});

export default function App() {
  const [ticks, setTicks] = useState(0);
  const [items, setItems] = useState(books.slice(0, 6));
  return (
    <Profiler id="ReadingList" onRender={onRender}>
      <button onClick={() => setTicks((t) => t + 1)}>Unrelated update ({ticks})</button>{" "}
      <button onClick={() => setItems((list) => [...list].reverse())}>Reverse the list</button>
      <BookList items={items} />
    </Profiler>
  );
}
Nothing logged yet.

The mount logs a large actualDuration (six rows at 3ms or more). "Unrelated update" logs a tiny actualDuration but the same large baseDuration: memo skipped the list, and the Profiler shows you exactly what that saved. "Reverse the list" changes items, so the list re-renders and actualDuration jumps back up.

A few rules:

  • onRender runs during the commit, so keep it cheap and never set state in it (that would schedule another render, which calls onRender again). Aggregate into a variable or send batches to an analytics endpoint.
  • Profilers nest, and you can have as many as you like. Each adds some overhead, so wrap the regions you care about, not every component.
  • It's disabled in normal production builds. In the production build of React, <Profiler> renders its children and never calls onRender. Switch this sandbox to the production build and the console stays empty. To measure in production you need React's profiling build: alias react-dom/client to react-dom/profiling in your bundler, or run next build --profile in Next.js. It's slightly slower than the normal production build, so it's usually shipped to a small share of sessions, if at all.

For everyday investigation you don't need any of this: the React DevTools Profiler and, since React 19.2, the React tracks in the browser's Performance panel show the same data visually. Measure first covers those. <Profiler> is for when you want the numbers in code.

Pitfalls#

Check your understanding#

Quick checkactualDuration versus baseDuration

After an update, a Profiler reports actualDuration 0.4ms and baseDuration 18ms. What does that mean?

Explain it out loudPortals and modals

An interviewer asks: "What is a portal, how do events behave with it, and what else do you need to build an accessible modal?"

Interview angle

Say it in 30 seconds

createPortal(children, domNode) renders children into another DOM node, usually document.body, so modals and tooltips escape overflow: hidden and stacking contexts. Only the DOM placement changes: context, state and React's synthetic events still follow the React tree, so a click inside a portaled modal bubbles to the component that rendered it, while native DOM listeners never see it. A portal doesn't make a modal accessible; you still need dialog semantics, focus management, inert and Escape. <Profiler> reports render timings per commit through onRender, and it only works in development or a profiling build.

When do you need a portal?

basic

How do events behave inside a portal?

intermediate

What does an accessible modal need beyond a portal?

senior

What does <Profiler>'s onRender tell you?

intermediate

Can you use <Profiler> in production?

senior

Recap#

  • createPortal(children, domNode) renders DOM outside the parent's node, which escapes overflow clipping and stacking contexts for modals, tooltips and toasts.
  • A portal changes DOM placement only. Context, state ownership and synthetic event bubbling follow the React tree, so parents receive events from their portaled children; native DOM listeners don't.
  • Accessible modals need dialog semantics, focus in and back, inert on the background and Escape. Native <dialog> with showModal() provides much of it.
  • <Profiler id onRender> reports phase, actualDuration, baseDuration, startTime and commitTime per commit. The gap between actual and base shows what skipping saved.
  • Profiler is a no-op in normal production builds; use the profiling build (react-dom/profiling, next build --profile) to measure in production.

Sources#