The useId
hook in React is useful for generating unique IDs that you can use for accessibility or to avoid conflicts when multiple elements need the same ID in a component.
Why Use useId
?
Sometimes, you need unique IDs for elements, like in forms where labels and inputs need to be connected. useId
helps generate these IDs automatically, ensuring they are unique, even if you use the same component multiple times.
How to Use useId
-
Import
useId
from React: You first need to importuseId
at the top of your component.
import { useId } from 'react';
-
Using
useId
to Generate Unique IDs: Inside your component, calluseId
to generate an ID. This ID can then be used for any HTML element.
function MyForm() {
const id = useId(); // Generate a unique ID
return (
<div>
<label htmlFor={id}>Username:</label>
<input id={id} type="text" />
</div>
);
}
Explanation:
-
useId()
generates a unique ID when the component is rendered. - We assign that unique ID to both the
<label>
(htmlFor={id}
) and the<input>
(id={id}
) elements. This connects the label to the input.
-
Result:
When React renders the component,
useId
will generate something like:r0:
or:r1:
for theid
values. This ensures that even if you use multiple<MyForm />
components on the page, each input field will have a unique ID.
Key Points:
-
useId
is helpful when building reusable components where IDs are needed. - The hook is especially useful when working with forms, accessibility, and ensuring unique IDs in complex components.
Top comments (0)