React / 85
useId: unique ids for labels and inputs
useId gives each component instance its own stable id that matches on the server and in the browser. Use it to link labels, inputs and hints. Never use it for list keys.
The shape
import { useId } from "react";
export default function EmailField({ label }) {
const id = useId();
return (
<>
<label htmlFor={id}>{label}</label>
<input id={id} type="email" aria-describedby={`${id}-hint`} />
<p id={`${id}-hint`}>We only email about this order.</p>
</>
);
}useId()takes no arguments and returns a string.- Each component instance gets a different one, and it stays the same across re-renders.
- Need several related ids? Call it once and add suffixes:
${id}-hint,${id}-error.
In JSX the label attribute is htmlFor, because for is a JavaScript keyword.
<EmailField /> for billing and for delivery
copy 1 · billing
const id = useId() → "_r_1_"
<label htmlFor="_r_1_">
<input id="_r_1_" aria-describedby="_r_1_-hint" />
<p id="_r_1_-hint">
copy 2 · delivery
const id = useId() → "_r_2_"
<label htmlFor="_r_2_">
<input id="_r_2_" aria-describedby="_r_2_-hint" />
<p id="_r_2_-hint">
Same component, different ids
Try itWe only email about this order.
useId() → "_R_1b6lalubsnnb_"
We only email about this order.
useId() → "_R_2b6lalubsnnb_"
Why not a counter or Math.random()?
Don't
Make up your own id
function EmailField() {
const id = "email-" + Math.random();
// or: const id = "email-" + nextId++;
return <input id={id} />;
}Math.random() changes on every render. With server rendering, the server and browser also make different ids, so React reports a hydration mismatch.
Do
Ask React for one
function EmailField() {
const id = useId();
return <input id={id} />;
}React builds the id from the component's position in the tree, so it's stable and matches on the server and in the browser.
When you don't need it
If the input sits inside its label, they're linked without any id:
<label>
Email
<input type="email" />
</label>You still need ids for anything else that points at an element: aria-describedby, aria-labelledby, aria-controls, or a label that can't wrap its input.
Gotchas
Recall
Can you answer these?
0/4
Answer out loud (or in your head) before you tap. That's what makes it stick.
Saved on this device only. No login.
