useId
useId is a React Hook for generating unique IDs that can be passed to accessibility attributes.
const id = useId()Reference
useId()
Call useId at the top level of your component to generate a unique ID:
import { useId } from 'react';
function PasswordField() {
const passwordHintId = useId();
// ...Parameters
useId does not take any parameters.
Returns
useId returns a unique ID string associated with this particular useId call in this particular component.
Caveats
-
useIdis a Hook, so you can only call it at the top level of your component or your own Hooks. You canโt call it inside loops or conditions. If you need that, extract a new component and move the state into it. -
useIdshould not be used to generate keys in a list. Keys should be generated from your data.
Usage
Generating unique IDs for accessibility attributes
Call useId at the top level of your component to generate a unique ID:
import { useId } from 'react';
function PasswordField() {
const passwordHintId = useId();
// ...You can then pass the generated ID to different attributes:
<>
<input type="password" aria-describedby={passwordHintId} />
<p id={passwordHintId}>
</>Letโs walk through an example to see when this is useful.
HTML accessibility attributes like aria-describedby let you specify that two tags are related to each other. For example, you can specify that an element (like an input) is described by another element (like a paragraph).
In regular HTML, you would write it like this:
<label>