The useId
hook in React generates unique, stable IDs that remain consistent across both server-side and client-side rendering.
This hook is primarily intended for accessibility purposes, helping ensure that elements such as form inputs and labels have unique identifiers.
It also helps avoid ID collisions, making it especially useful when building reusable components that require unique IDs for multiple instances.
Example
import React, { useId } from 'react';
function LabeledInput({ label }) {
const inputId = useId();
return (
<div>
<label htmlFor={inputId}>{label}</label>
<input type="text" id={inputId} />
</div>
);
}
function MyForm() {
return (
<div>
<LabeledInput label="First Name" />
<LabeledInput label="Last Name" />
<LabeledInput label="Email" />
</div>
);
}
export default MyForm;
In this example:
useId()
generates a unique ID for eachLabeledInput
component.- The generated
inputId
is used to connect the<label>
and<input>
elements via thehtmlFor
andid
attributes, respectively. - This ensures that each input has a unique ID, even when the
LabeledInput
component is used multiple times within theMyForm
. This is crucial for accessibility, so screen readers can correctly associate the labels with their inputs.
Note: If a static id was used, instead of a unique ID generated by useId
hook, such as "myInput"
, there would be id collisions.