Home
React
React Hook: useId()
Daniel Nguyen
Daniel Nguyen
July 09, 2025
1 min

useId is a React Hook that generates a unique, stable ID for each component instance. It is especially useful for connecting form inputs with labels, hints, and accessibility attributes.

1. The Problem: Duplicate IDs

HTML labels use htmlFor and id to associate a label with an input.

function TextField() {
return (
<>
<label htmlFor="email">Email</label>
<input id="email" />
</>
);
}

This works for one instance, but rendering the component multiple times creates duplicate IDs.

<TextField />
<TextField />

Duplicate IDs violate HTML requirements and can cause labels and accessibility relationships to target the wrong element.

2. The Solution: useId

Use useId to generate an ID for each component instance.

import { useId } from "react";
function TextField({ label, hint }) {
const id = useId();
const hintId = `${id}-hint`;
return (
<div>
<label htmlFor={id}>{label}</label>
<input id={id} aria-describedby={hintId} />
<p id={hintId}>{hint}</p>
</div>
);
}

Now each instance has its own ID, and aria-describedby connects the input to its corresponding hint.

<TextField label="Email" hint="Enter your email address." />
<TextField label="Password" hint="Use a strong password." />

React generates IDs that remain stable across re-renders and supports consistent IDs between server rendering and client hydration when the component trees match.

3. When Not to Use useId

useId is designed for accessibility-related DOM relationships, not general-purpose identifiers.

  • List keys: Use stable data IDs.
  • Database IDs: Generate identifiers through your data layer.
  • Random values: Use an appropriate random or unique ID generator when needed.
// ❌ Incorrect
items.map(() => <Row key={useId()} />);
// ✅ Correct
items.map((item) => <Row key={item.id} />);

Hooks must be called at the top level of a component or custom Hook, not inside loops or callbacks.


Tags

#ReactHook

Share

Daniel Nguyen

Daniel Nguyen

Frontend Developer

Frontend developer specializing in React, Next.js, and JavaScript. Writing practical guides on modern web development at Dev98.

Expertise

React
Next.js
JavaScript
TypeScript
Python

Social Media

githublinkedinyoutubewebsite

Related Posts

React Hook
React Hook: useRef()
July 10, 2025
1 min
Dev98

Dev98

React · Next.js · Web development