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();
// ...

See more examples below.

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

  • useId is 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.

  • useId should not be used to generate keys in a list. Keys should be generated from your data.


Usage

Pitfall

Do not call useId to generate keys in a list. Keys should be generated from your data.

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>