DEV Community

Cover image for useId
Pritpal Singh
Pritpal Singh

Posted on

useId

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

  1. Import useId from React: You first need to import useId at the top of your component.
   import { useId } from 'react';
Enter fullscreen mode Exit fullscreen mode
  1. Using useId to Generate Unique IDs: Inside your component, call useId 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>
     );
   }
Enter fullscreen mode Exit fullscreen mode

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.
  1. Result: When React renders the component, useId will generate something like :r0: or :r1: for the id 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)