The useId
hook in React is designed to generate unique IDs that are stable across server and client renders. This is particularly useful for accessibility purposes, such as associating form inputs with labels, and ensuring that IDs are unique even when multiple instances of a component are rendered.
Simple Explanation
The useId
hook generates a unique identifier that you can use for elements like form inputs and labels. This helps avoid issues with duplicate IDs when you have multiple instances of a component on the same page.
Basic Usage
Here’s a simple example of how to use useId
:
import { useId } from 'react';
function MyComponent() {
const id = useId();
return (
<div>
<label htmlFor={id}>Name:</label>
<input id={id} type="text" />
</div>
);
}
In this example, useId
generates a unique ID that is used for both the label
and the input
elements.
Examples
- Form Input and Label:
import { useId } from 'react';
function FormComponent() {
const inputId = useId();
return (
<div>
<label htmlFor={inputId}>Name:</label>
<input id={inputId} type="text" />
</div>
);
}
- Multiple Form Fields:
import { useId } from 'react';
function MultiFieldForm() {
const nameId = useId();
const emailId = useId();
return (
<div>
<label htmlFor={nameId}>Name:</label>
<input id={nameId} type="text" />
<label htmlFor={emailId}>Email:</label>
<input id={emailId} type="email" />
</div>
);
}
- Dynamic List Items:
import { useId } from 'react';
function DynamicList({ items }) {
return (
<ul>
{items.map((item) => {
const itemId = useId();
return (
<li key={itemId}>
<label htmlFor={itemId}>{item.label}</label>
<input id={itemId} type="text" defaultValue={item.value} />
</li>
);
})}
</ul>
);
}
- Accessible Checkbox:
import { useId } from 'react';
function CheckboxComponent() {
const checkboxId = useId();
return (
<div>
<input type="checkbox" id={checkboxId} />
<label htmlFor={checkboxId}>Agree to terms</label>
</div>
);
}
- Unique IDs in a Table:
import { useId } from 'react';
function DataTable({ rows }) {
return (
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
</tr>
</thead>
<tbody>
{rows.map((row) => {
const rowId = useId();
return (
<tr key={rowId}>
<td>{rowId}</td>
<td>{row.name}</td>
</tr>
);
})}
</tbody>
</table>
);
}
Practice Exercises
- Create a component that generates unique IDs for multiple form fields using
useId
. - Build a component that dynamically generates a list of items with unique IDs for each item using
useId
. - Develop a component that uses
useId
to create accessible checkboxes and labels. - Implement a component that uses
useId
to generate unique IDs for table rows. - Create a component that uses
useId
to generate unique IDs for a set of radio buttons and their labels.
These exercises will help you get comfortable with using the useId
hook in various scenarios.