React Reference ยท State Hooks
React useId hook
Reference for React useId: generate stable, unique IDs for labels, aria attributes and form fields that match between server and client and never collide.
useId returns a unique string that stays the same for the lifetime of a component instance. Its main job is linking elements through attributes such as htmlFor/id, aria-describedby and aria-labelledby, without hard-coding names that would collide when a component is used twice.
The ID is generated from the component's position in the tree, so the server and the browser produce the same value. That makes it safe for server rendering and hydration, which counters or Math.random() are not.
const id = useId(); return ( <> <label htmlFor={id}>Email</label> <input id={id} type="email" /> </> );
Try it
Clicking either label focuses its own input, because each instance got a different ID.
Syntax
const id = useId();
function useId(): string;
| Name | Description |
|---|---|
| (none) | useId takes no arguments. |
Returns: a string that is unique within the app and stable across renders of the same instance. In React 19.2 and later it looks like _r_0_ (React 18 used :r0:, React 19.1 used ยซr0ยป); never depend on the exact format.
Usage notes
- Not for list keys. Keys must come from your data. Calling
useIdfor each item inside a.mapwould also break the rules of hooks. - Add suffixes for several elements. Call it once per component and derive more IDs:
id + '-hint',id + '-error'. - Not for CSS selectors. The generated characters are not guaranteed to be valid in
querySelectorwithout escaping, and the format may change. - Server rendering: IDs match on the server and the client as long as the tree structure is the same. That avoids hydration mismatches.
- Several roots on one page: pass
identifierPrefixtocreateRoot/hydrateRootso IDs from different roots cannot collide. - Not a secret or a database ID. It identifies a component instance, not data, and changes if the component is remounted.
- Don't generate it by hand. A module-level counter or
Math.random()creates hydration mismatches and different IDs between StrictMode's double renders. - Reusable components benefit most: form inputs, tooltips, dialogs, tabs and accordions, anything that links two elements by ID.
Related
- useState, useDebugValue, useRef
- Lessons: Accessibility, Forms and inputs