React - useId Hook

Published on
3 mins read
––– views

What is React useId hook?

When building user interfaces that are accessible to everyone, it's important to use unique IDs for labels and input fields. This is particularly helpful for people who use screen readers or have limited mobility. Unique IDs help accessibility software to understand the page and provide a better user experience.

To generate unique IDs and assign them to labels and input fields, we can use the useId hook from the React-Aria package. When we call this hook, it generates a unique ID using a built-in counter function. This counter function increments the generated ID each time we need a new one. Once we've generated the necessary IDs, we can pass them to different attributes and link elements together.

To use the useId hook, we simply call it and store the result in a variable:

const id = React.useId()

We can then use this ID to create unique IDs for our labels and input fields:

const usernameId = `${id}-username`
const passwordId = `${id}-password`

Each time we call useId, it generates a new, unique ID by incrementing a built-in counter. This means we don't have to worry about naming our IDs manually when building large forms.

For example, if we have two input fields like this:

<input
          type="text"
          id={usernameId}
          value={username}
          onChange={(event) => {
            setUsername(event.target.value);
          }}
        />
        /// second input
        <input
          type="text"
          id={usernameId}
          value={username}
          onChange={(event) => {
            setUsername(event.target.value);
          }}
        />

What would be the output if I console.log the usernameId?

- logs
:r0:-username
:r1:-username

As we discovered earlier, the useId hook comes with a handy built-in counter function that increments the ID each time it's called. This means you can generate unique IDs for your form elements without worrying about naming conflicts, even in large forms.

Using the useId hook can save you the trouble of manually creating and assigning IDs to each input field, which can be especially helpful when building forms with many input elements. By doing so, you can ensure that each element has a unique ID, which can improve the accessibility and overall user experience of your application.