Sub topic 12
Pitfalls and best practices
This chapter assumes you can build a portal-based modal with createPortal, and that you know how React events bubble through the component tree. You should also be comfortable with useEffect cleanup. The chapter collects the mistakes that show up most often in real portal code and gives a fix for each one.
Why portals fail in a few repeatable ways
A portal changes where nodes appear in the DOM and leaves the React tree unchanged. Most portal bugs come from forgetting which of the two trees a given mechanism follows.
| Mechanism | Follows |
|---|---|
| React event handlers (`onClick`) | React tree |
| Context and state | React tree |
| Native listeners (`addEventListener`) | DOM tree |
| CSS selectors and inherited styles | DOM tree |
| `element.contains()` | DOM tree |
| Stacking contexts and `overflow` clipping | DOM tree |
| Focus order and screen reader reading order | DOM tree |
When something behaves unexpectedly, find which tree the mechanism uses and check whether the portal moved the node out of the place you assumed.
Pitfall 1: The container does not exist
createPortal(children, null) throws "Target container is not a DOM element". The most common cause is a lookup like document.getElementById('portal-root') that runs before the element exists. Three situations produce this:
- The
<div id="portal-root">was never added toindex.html. - The code runs on the server, where
documentis undefined. - The lookup happens in a module's top level, before the page has been parsed.
Look up the container inside an effect, as the ClientPortal example earlier in this tutorial does, or create the node yourself. A self-managed container removes the dependency on markup:
import { useEffect, useState } from 'react';
import { createPortal } from 'react-dom';
function Portal({ children }) {
const [node, setNode] = useState(null);
useEffect(() => {
const el = document.createElement('div');
document.body.appendChild(el);
setNode(el);
return () => {
document.body.removeChild(el);
};
}, []);
return node ? createPortal(children, node) : null;
}Create the element in an effect and never during render. Render can run more than once, and React can throw away a render without committing it. A document.createElement call plus appendChild in the render body leaves orphaned div elements in the page. The effect's cleanup removes the node, so Strict Mode's extra mount and unmount cycle in development leaves nothing behind.
The cost of this approach is that content appears one render later, because node starts as null. For modals that open on a user action this is invisible. For content that must be present on first paint, use a container that already exists in the HTML.
Pitfall 2: Rendering into a node React also manages
Do not pass a node as the container if React renders other children into that same node. React assumes it owns everything inside the nodes it controls. If two parts of your code add and remove children in the same element, React can fail to find nodes it expects to remove.
Using document.body is allowed. Several portals can share it, because each portal adds and removes only its own children. The problem arises only when you target an element that another component renders and updates.
Pitfall 3: Listeners that outlive the component
Portal components often attach listeners to document or window, for Escape handling, outside clicks, or resize tracking. These are the most common source of leaks. Two mistakes recur.
The first is a missing cleanup. The second is a listener that is removed and re-added on every render because the callback identity changes. The useEscapeKey hook earlier in this tutorial lists onEscape as a dependency. If the parent passes an inline arrow function, the effect re-runs on each render. That is correct but wasteful, and it can reorder listeners when several modals are open. Store the latest callback in a ref and subscribe once:
import { useEffect, useRef } from 'react';
function useEscapeKey(onEscape) {
const latest = useRef(onEscape);
useEffect(() => {
latest.current = onEscape;
});
useEffect(() => {
function handleKeyDown(event) {
if (event.key === 'Escape') latest.current();
}
document.addEventListener('keydown', handleKeyDown);
return () => document.removeEventListener('keydown', handleKeyDown);
}, []);
}Scroll locking has the same shape of problem, with an extra trap. Setting document.body.style.overflow = 'hidden' in a modal and resetting it to '' on close breaks when two modals overlap. The first modal to close unlocks the page while the second is still open. Count the active locks and restore the original value only when the count reaches zero:
import { useEffect } from 'react';
let lockCount = 0;
let previousOverflow = '';
function useScrollLock(active) {
useEffect(() => {
if (!active) return undefined;
if (lockCount === 0) {
previousOverflow = document.body.style.overflow;
document.body.style.overflow = 'hidden';
}
lockCount += 1;
return () => {
lockCount -= 1;
if (lockCount === 0) {
document.body.style.overflow = previousOverflow;
}
};
}, [active]);
}Pitfall 4: Click-outside logic that ignores the two trees
A dropdown whose menu is portaled to document.body is no longer a DOM descendant of its trigger. A typical "close when the click lands outside the component" check uses ref.contains(event.target) on the wrapper. That check sees the menu as outside, so clicking a menu item closes the dropdown before the item's handler can act on the click.
Check every DOM node that counts as inside: the trigger and the portaled menu.
import { useEffect, useRef, useState } from 'react';
import { createPortal } from 'react-dom';
function Dropdown() {
const [open, setOpen] = useState(false);
const buttonRef = useRef(null);
const menuRef = useRef(null);
useEffect(() => {
if (!open) return undefined;
function handlePointerDown(event) {
const inside =
buttonRef.current?.contains(event.target) ||
menuRef.current?.contains(event.target);
if (!inside) setOpen(false);
}
document.addEventListener('pointerdown', handlePointerDown);
return () => document.removeEventListener('pointerdown', handlePointerDown);
}, [open]);
return (
<>
<button ref={buttonRef} onClick={() => setOpen((o) => !o)}>
Menu
</button>
{open &&
createPortal(
<ul ref={menuRef} role="menu">
<li role="menuitem">Profile</li>
<li role="menuitem">Sign out</li>
</ul>,
document.body
)}
</>
);
}The reverse mistake also exists. A React onClick on an ancestor of a portal fires for clicks inside the portal, because React events bubble through the React tree. If that ancestor means "the user clicked my card, navigate to the detail page", clicks inside a modal rendered by a child will navigate too. Fix it at the portal boundary with stopPropagation, as the Modal example does, or by checking event.currentTarget.contains(event.target) in the ancestor's handler. The contains check works because it uses the DOM tree: it is false for portaled content.
Note that stopPropagation on a React synthetic event stops React's own bubbling. A native listener on document is a separate system, so you can still see the event there.
Pitfall 5: Styles that depended on the old parent
CSS follows the DOM. Once content moves to document.body, it no longer matches selectors such as .card .tooltip or .theme-dark .button, and it no longer inherits font-family, color, or CSS custom properties set on a wrapper below body. The symptom is a modal that looks unstyled or in the wrong theme, even though context correctly says "dark".
Fixes, in order of preference:
- Put design tokens (CSS variables, fonts, base colors) on
:rootorbodyso every container inherits them. - Apply theme classes to the portal container, using a value read from context inside a component.
- Style portal content with classes that do not depend on an ancestor, such as
.dialograther than.page .dialog.
Stacking has a related trap. A portal into body escapes the clipping and stacking context of its original parent, but it still competes with every other top-level element. If the app root creates its own stacking context with a high z-index, the portal can end up behind it. Give the app root isolation: isolate with no explicit z-index, and give portal containers a defined layer, for example a z-index on #portal-root. Define a small set of layer values (dropdown, modal, toast) in one place instead of choosing numbers per component.
Pitfall 6: Accessibility that stops at the visual layer
A portal puts content at the end of body, so the keyboard Tab order and the screen reader reading order now place the dialog after the whole page. Visual presence is not enough. For a modal you should do all of these:
- Set
role="dialog",aria-modal="true", and an accessible name witharia-labelledbyoraria-label. - Move focus into the dialog when it opens, and return focus to the element that opened it when it closes.
- Keep Tab from leaving the dialog, either with a focus trap or by marking the rest of the page
inert. - Close on Escape.
The inert attribute on the app root is the simplest reliable approach in current browsers. It removes the page from the tab order and the accessibility tree without custom focus-trap code. Where you must support older browsers, use a tested library such as focus-trap-react instead of writing your own.
Restoring focus is the step most often forgotten. Capture document.activeElement before opening and call .focus() on it during cleanup.
Pitfall 7: Identity, state, and server rendering
Switching the container changes the portal's identity. If the container argument changes between renders, React unmounts the children from the old node and mounts them into the new one, which resets their state. Keep the container stable, or accept the reset knowingly.
Conditional rendering matters too. State lives in the React tree, so {open && createPortal(...)} discards the dialog's state when open becomes false. Closing and reopening gives a fresh form. If you want to keep the state, keep the portal mounted and hide it, or lift the state into a parent.
For server rendering, remember that document does not exist on the server, so the container lookup must wait for an effect. The ClientPortal pattern handles this and avoids a hydration mismatch, because the server and the first client render both output null.
Debugging checklist
Best practices summary
- Use one or a few well-known containers, such as
#portal-root, and never one that React renders. - Create DOM nodes in effects, and remove them in the cleanup.
- Pair every
addEventListenerwith aremoveEventListener, and keep the effect's dependencies stable by using a ref for the latest callback. - Treat scroll lock as shared state, with a counter.
- Decide for each handler whether it should see portal events, and stop propagation at the boundary if not.
- Put design tokens on
:rootso portal content inherits them. - Query portal content in tests with
screen, which searchesdocument.body, instead of thecontainerreturned byrender. - Reserve portals for content that needs to escape clipping or stacking. If a plain
position: fixedelement works inside the parent, it is simpler.
Exercise
A card component has an onClick that navigates to a detail page. A child component opens a portaled modal with a "Delete" button. Clicking "Delete" also navigates away. Why does this happen, and what are two ways to fix it?
Show answer
React synthetic events bubble through the React tree, and the modal is still a React descendant of the card, even though its DOM nodes sit in document.body. The click on "Delete" therefore reaches the card's onClick. One fix is to call event.stopPropagation() in an onClick on the modal's outer element, so the click never reaches the card. The other is to make the card's handler check event.currentTarget.contains(event.target) and return early when it is false, because portaled nodes are not DOM descendants of the card.
Exercise
Your dropdown menu is rendered through a portal. Clicking a menu item closes the menu without running the item's action. The close logic is a document pointerdown listener that tests wrapperRef.current.contains(event.target). What is wrong and how do you fix it?
Show answer
The wrapper contains only the trigger in the DOM. The menu was moved to document.body, so contains returns false for clicks on menu items, and the listener closes the menu on pointerdown, before the item's click fires. Keep a ref to the menu as well, and treat the click as inside when either the trigger ref or the menu ref contains event.target.