What is the useId hook and how does it improve accessibility
· Category: React
Short answer
useId generates a unique, stable identifier string that is consistent across server and client renders. It is ideal for linking form inputs with labels and ARIA attributes.
How it works
React ensures the generated ID is unique within the component tree and does not clash with other IDs. Unlike Math.random(), it is deterministic for SSR hydration.
Example
import { useId } from 'react';
function EmailField() {
const id = useId();
return (
<>
<label htmlFor={id}>Email</label>
<input id={id} type="email" />
</>
);
}
Tips
- Do not use
useIdfor list keys; keys must come from your data. - Combine with a suffix if you need multiple IDs in one component.
- Available in React 18+. For older versions, use a counter or UUID library.