ReactEasy
What is useId?
useId() generates a unique ID string that stays the same between server and client renders, so it is safe for server rendering and hydration. Use it to connect accessibility attributes, such as a <label htmlFor> with an <input id>, or aria-describedby with a hint element, in reusable components.
Why not Math.random() or a counter
- Random IDs differ between the server HTML and the client render, causing hydration mismatches.
- Global counters break with streaming and concurrent rendering, where components can render in different orders.
useIdderives the ID from the component's position in the tree, so it matches on both sides.
Usage
- Call once per component and derive related IDs:
const id = useId(); id + "-hint". - The ID contains special characters (React 19.2 uses an
_r_prefix, earlier versions used colons or«r»), so it is valid foridattributes but awkward in CSS selectors; do not use it inquerySelectorwithout escaping. identifierPrefixoncreateRoot/hydrateRootavoids clashes when several React roots share a page.
Not for
- List keys: keys should come from your data.
- Database or entity IDs: use
crypto.randomUUID()when creating records.
Accessibility pattern
Every reusable form field should use useId so multiple instances on one page never share IDs.
Code example
tsx
1import { useId } from "react";23export function PasswordField({ label = "Password" }: { label?: string }) {4 const id = useId(); // e.g. "_r_1_" - identical on server and client56 return (7 <div>8 <label htmlFor={id}>{label}</label>9 <input id={id} type="password" aria-describedby={`${id}-hint`} />10 <p id={`${id}-hint`}>At least 12 characters, including a number.</p>11 </div>12 );13}1415// Two instances on the same page get different ids, no collisions16export function ChangePassword() {17 return (18 <form>19 <PasswordField label="Current password" />20 <PasswordField label="New password" />21 </form>22 );23}
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React set.