Sub topic 10
Portals and Server Rendering
This chapter covers what happens when a component that calls createPortal runs on the server, and how to make it safe. It assumes you can already build a portal-based modal, that you know useState and useEffect, and that you know the basic idea of server-side rendering (SSR). In SSR, React produces HTML on the server and the browser then attaches event handlers to it. That second step is called hydration.
Why portals and servers conflict
A portal needs a real DOM node as its target. The call looks like this:
createPortal(children, document.body)On the server there is no document and no body. Server rendering produces a string of HTML. It does not build a live DOM tree. This causes two separate problems.
- A reference error. If a component reads
document.bodyduring render, Node throwsReferenceError: document is not definedon the server. - Portals are not supported by the server renderer. Even if you obtained a container some other way,
renderToStringfromreact-dom/serverthrows an error saying portals are not currently supported by the server renderer. React asks you to render portals only on the client.
So a portal component needs a rule: on the server, render nothing. After the page reaches the browser, render the portal.
The naive fix and why it breaks hydration
A common first attempt is to check for document during render:
import { createPortal } from 'react-dom';
// Problematic: the server and the first client render disagree.
function BadPortal({ children }) {
if (typeof document === 'undefined') return null;
return createPortal(children, document.body);
}On the server this returns null. In the browser, the first render during hydration returns a portal. React compares what it renders on the client with the HTML the server sent. When they differ, React reports a hydration mismatch. Depending on the React version, it either logs a warning and patches the DOM, or discards the server HTML and re-renders the tree on the client. Either way you lose the benefit of server rendering for that part of the page.
The rule is that the first client render must produce the same output as the server render. For a portal component, that output is null.
The two-pass pattern
The fix is to render in two passes on the client.
- First pass (server and hydration): render
null. - Second pass (after mount): an effect runs, finds the container, stores it in state, and triggers a re-render that creates the portal.
Effects never run on the server, and they run only after hydration finishes. That makes the effect a reliable boundary between "no DOM guaranteed" and "DOM available".
import { useEffect, useState } from 'react';
import { createPortal } from 'react-dom';
function ClientPortal({ children, containerId = 'portal-root' }) {
const [container, setContainer] = useState(null);
useEffect(() => {
setContainer(document.getElementById(containerId));
}, [containerId]);
return container ? createPortal(children, container) : null;
}The sequence below shows the order of events.
If the container is missing, getElementById returns null. The component then keeps rendering null and shows nothing, with no error. This is the "missing container" pitfall from the general portal checklist, and it is easier to miss with SSR because the server HTML looks fine.
Where the container comes from
The container node must exist in the HTML that the server sends, or be created by your own code before the portal renders. There are two common setups.
- A node in the HTML shell. Add a sibling of your app root:
<body>
<div id="root"></div>
<div id="portal-root"></div>
</body>In a framework, this usually goes in the root layout or document template. Keep the portal root outside the React root so React never tries to hydrate it.
document.bodyitself. No extra node is needed, but you can only read it on the client.
Do not create the container node inside a render function. Render must stay free of side effects, and a render can run more than once. If you must create a node, do it inside an effect and remove it in the cleanup function.
import { useEffect, useState } from 'react';
import { createPortal } from 'react-dom';
function OwnedContainerPortal({ children }) {
const [container, setContainer] = useState(null);
useEffect(() => {
const node = document.createElement('div');
document.body.appendChild(node);
setContainer(node);
return () => {
document.body.removeChild(node);
};
}, []);
return container ? createPortal(children, container) : null;
}The cleanup function matters.aves a stray div in document.body. In development, React's Strict Mode mounts, unmounts and mounts again, so a missing cleanup shows up as duplicate nodes right away.
An alternative: useSyncExternalStore
The effect-and-state pattern works, but it needs a state variable for every portal. React also provides a hook that is designed for values that differ between server and client. useSyncExternalStore takes a separate getServerSnapshot function. React uses it on the server and during hydration, then switches to the client snapshot right after.
import { useSyncExternalStore } from 'react';
import { createPortal } from 'react-dom';
const subscribe = () => () => {};
function useIsClient() {
return useSyncExternalStore(
subscribe,
() => true,
() => false
);
}
function BodyPortal({ children }) {
const isClient = useIsClient();
return isClient ? createPortal(children, document.body) : null;
}The subscribe function does nothing because the answer to "are we on the client?" never changes. Defining it outside the component keeps its identity stable, so React does not resubscribe on every render.
Choosing between the approaches
| Approach | Strength | Weakness |
|---|---|---|
| `useEffect` plus state | Looks up any container by id. Easy to read. | One extra state variable per portal. |
| `useSyncExternalStore` | Short, reusable `useIsClient` hook. Written for server/client differences. | Only tells you "client or not". You still need a container, such as `document.body`. |
| Load the component only on the client (framework option, such as a dynamic import with server rendering off) | The component never runs on the server. | The whole component is missing from the server HTML. |
For a single modal, any of these is fine. Pick one and use it everywhere so the team recognizes the pattern.
What the server HTML contains
Because portal content is rendered after hydration, the server HTML never includes it. This has consequences:
- Search engines and non-JavaScript clients do not see portal content in the initial HTML. This is rarely a problem for modals, tooltips and menus, which are hidden at page load anyway. It is a problem if you portal content that should be indexed or that is visible on first paint. Do not use a portal for that content. Portals exist to escape clipping and stacking, so use one only when you need that.
- Visible content shifts. Portal content appears one render after the rest of the page. For overlays that open after a user action, this is invisible, because the user cannot click before hydration finishes anyway. For a banner that should show immediately, the delay can cause a flash.
- Initially open overlays. If a modal is open in the first render, for example because a URL parameter says so, the server HTML shows the page with no dialog. The dialog then appears after hydration. If this matters, design the page so it is usable without the dialog, or accept the short delay.
Streaming and Suspense
Streaming renderers send HTML in chunks, and React hydrates parts of the page as they arrive. The two-pass pattern works the same way under streaming. Each portal component renders null until its own hydration finishes, then runs its effect. You do not need special handling. The one thing to watch is a portal inside a Suspense boundary that has not loaded yet. Its effect does not run until the boundary resolves and hydrates, so the portal appears later than the rest of the page.
Testing the server behavior
You can check the server contract directly. With renderToString, a portal component should return an empty string and not throw.
import { renderToString } from 'react-dom/server';
import { ClientPortal } from './ClientPortal';
test('renders nothing on the server', () => {
const html = renderToString(
<ClientPortal>
<p>Hello</p>
</ClientPortal>
);
expect(html).toBe('');
});This test assumes ClientPortal is exported from ./ClientPortal. It also guards against a regression where someone replaces the effect with a direct document read. In a jsdom test environment document exists, so a direct read would not fail this test by itself. A Node test environment (@jest-environment node in Jest) makes the test stricter, because there document is truly undefined.
Pitfalls specific to SSR
- Reading
documentduring render. It throws on the server. Read it in an effect, or behinduseSyncExternalStore. - Checking
typeof documentand rendering a portal. The server and first client render disagree, which causes a hydration mismatch. - Putting the portal root inside the React root. React may try to hydrate it and complain when the contents differ. Keep it a sibling.
- Creating container nodes without cleanup. You get leaked nodes, especially under Strict Mode.
- Forgetting the client-component marker. In frameworks that split server and client components, such as the Next.js App Router, a file that uses
useEffect,useStateorcreatePortalneeds the'use client'directive at the top. Without it, the framework reports an error about hooks in a server component. - Using a portal for content that should be in the server HTML. If it must be indexable or visible on first paint, do not portal it.
Summary of the working model
- The server cannot create portals, so a portal component renders
nullthere. - The first client render must match the server, so it also renders
null. - After hydration, an effect (or
useSyncExternalStore) switches the component into client mode. - The portal then renders into a container that exists in the browser, and any container you create yourself is removed in a cleanup function.
Exercise
A teammate writes function Tip({ children }) { return typeof document === 'undefined' ? null : createPortal(children, document.body); }. It does not crash on the server, but React logs a hydration mismatch in the browser. Why does the mismatch happen, and how would you fix it?
Show answer
On the server document is undefined, so the component renders null and the HTML has no tooltip. In the browser document exists from the first render, so the first client render returns a portal. The server output and the first client render differ, which is a hydration mismatch. The fix is to render null on the first client render too. Either store the container in state inside useEffect, or use a useIsClient hook built on useSyncExternalStore with () => false as the server snapshot. Then create the portal only after that value turns true.
Exercise
Your OwnedContainerPortal creates a div in document.body inside useEffect. After a few hot reloads in development, the page has several empty div elements at the end of body. What is missing from the effect, and why does Strict Mode make the problem visible?
Show answer
The effect does not return a cleanup function, so the div is never removed when the component unmounts or the effect re-runs. The fix is to return a function that calls document.body.removeChild(node). In development, Strict Mode mounts, unmounts and remounts each component to expose missing cleanups, so each leaked mount adds another div.