Sub topic 8
Matching ids on server and client with useId
This chapter assumes you can write function components with useState and useEffect. It also assumes you know how renderToPipeableStream and hydrateRoot fit together, and why a hydration mismatch happens. Here you will fix one specific kind of mismatch: generated ids that differ between the server and the browser.
Why generated ids cause mismatches
Form fields need ids. A <label> points at an <input> through htmlFor and id, and ARIA attributes such as aria-describedby point at other elements by id. When one component renders many times on a page, each copy needs its own unique id.
The usual first attempt is a counter or a random number:
let nextId = 0;
function BadEmailField() {
const id = `email-${nextId++}`;
return (
<>
<label htmlFor={id}>Email</label>
<input id={id} type="email" />
</>
);
}This breaks under server rendering for two reasons:
- A module-level counter lives for as long as the Node.js process runs. The server renders many requests, so the counter keeps growing and the value for the first field differs from request to request. The browser starts its own counter at 0, so the two values will not agree.
Math.random()gives a different value on every call, so the server and the client always disagree.
During hydration, React compares the attributes it expects with the ones in the server HTML. A mismatched id or htmlFor produces a warning in development. The label and input in the server HTML may also no longer be linked to each other. If that is the only problem, React may keep the server value instead of patching the attribute. In that case the page can look fine while the label and input stay wired to the wrong ids. That is why you should fix id mismatches rather than ignore them.
What useId does
useId is a hook that returns a string. The string is unique within the app and identical on the server and the client for the same component in the same place in the tree.
import { useId } from 'react';
function EmailField() {
const id = useId();
return (
<>
<label htmlFor={id}>Email</label>
<input id={id} type="email" />
</>
);
}React does not use a global counter. It derives the id from the component's position in the tree, a bit like a path. The server and the client render the same tree, so both arrive at the same path and therefore the same id. The order in which requests arrive, or in which Suspense boundaries finish, has no effect on the result.
What the returned string looks like
The format has changed between React versions. React 18 returns strings like :r1:, and later releases use other formats. Treat the value as opaque. Pass it to id, htmlFor, and ARIA attributes, and nothing else.
Do not parse the string or compare it to a literal. Because the format contains characters that are special in CSS, such as the colon in the older format, document.querySelector('#' + id) can fail. If you need to select by id, use document.getElementById(id), or better, use a ref.
Several ids in one component
Call useId once per component and add suffixes for the other elements:
import { useId } from 'react';
function PasswordField() {
const id = useId();
const hintId = `${id}-hint`;
return (
<>
<label htmlFor={id}>Password</label>
<input id={id} type="password" aria-describedby={hintId} />
<p id={hintId}>Use at least 12 characters.</p>
</>
);
}One call is enough, and the suffixes are deterministic, so they match on both sides. Calling useId several times in one component also works, but one call plus suffixes is easier to read.
Rules and gotchas
Call it like any other hook
Call useId at the top level of a component or a custom hook. Do not call it inside loops, conditions, or callbacks. React tracks hooks by call order.
Do not use it for list keys
An id from useId identifies one component instance. It is not a key for items in a list. Keys should come from your data, such as a database id, so that React can match items across renders.
function Tags({ tags }) {
return (
<ul>
{tags.map((tag) => (
<li key={tag.id}>{tag.name}</li>
))}
</ul>
);
}Tree shape must match
Because the id depends on position, the server and the client must render the same tree shape. If the server renders a wrapper <div> and the client does not, the components below it sit at different positions and get different ids. You then see a mismatch that looks like an id problem, although the real cause is the tree shape. This is the same class of bug as reading window during render. Fix the divergent branch rather than the id.
The id is not a stable identity across time
The id stays the same while the component instance stays mounted. If the component unmounts and mounts again, you may get a different id. Do not store it in a database or use it as a persistent identifier.
Several React roots on one page
If two separate React roots are on the same page, both would produce ids from the root of their own tree and could collide. Give each root a distinct identifierPrefix. The server and the client must use the same prefix for the same root, or the ids will not match.
import { hydrateRoot } from 'react-dom/client';
import Widget from './Widget.js';
const container = document.getElementById('widget-root');
hydrateRoot(container, <Widget />, {
identifierPrefix: 'widget-'
});On the server, pass the same string in the options of renderToPipeableStream:
const { pipe } = renderToPipeableStream(<Widget />, {
identifierPrefix: 'widget-',
onShellReady() {
pipe(res);
}
});A single root rendered into the whole document does not need a prefix.
Choosing the right tool for an id-like problem
Different mismatch sources need different fixes, and useId only covers one of them.
| Situation | Use |
|---|---|
| Id for `htmlFor`, `aria-*`, or similar attributes | `useId` |
| Key for a list item | A key from your data |
| Current time or a random display value | A state value set in an effect |
| Browser-only state such as `navigator.onLine` | `useSyncExternalStore` with `getServerSnapshot` |
| Id that must be selected with CSS | A class name or a data attribute, not the generated id |
A quick debugging check
If a hydration warning names an id or htmlFor attribute, work through these steps:
- Search the component and its dependencies for
Math.random,Date.now,uuid, and module-level counters used during render. - Replace them with
useId. - Check that the tree above the component renders the same on the server and the client.
- If two roots share the page, set matching
identifierPrefixvalues on the server and the client.
Exercise
A page renders the same SearchBox component twice, once in the header and once in the footer. It builds its input id with Math.random(), and the development console shows a hydration warning about id. What do you change, and why does the new version match on the server and the client?
Show answer
Replace Math.random() with const id = useId(); and pass id to both the <label htmlFor> and the <input id>. useId derives the id from the component's position in the tree. The server and the client render the same tree, so each copy of SearchBox gets the same id on both sides. The header copy and the footer copy sit at different positions, so they get different ids and do not collide.
Exercise
Your app has two independent React roots on one page, and both call useId in components near the top of their trees. What option do you set, where do you set it, and what must be true about its value?
Show answer
Set identifierPrefix to a different string for each root. Set it in the options of hydrateRoot in the browser and in the options of renderToPipeableStream on the server. For each root, the server and the client must use the same string. Each root needs its own distinct prefix so that ids from the two roots cannot collide.