When to Use the React useId() Hook?

The useId() hook should only be used to generate a unique identifier for the id attribute of an HTML element for purposes such as:

  • Associating form labels with input fields, or;
  • Adding accessibility attributes (such as aria-describedby).

Using the useId() hook has the added benefit that it works well with hydration of server-side rendered components by generating a unique and stable identifier that can be used reliably across the server and client side of the application.

Please note that you should not use the identifier generated by the useId() hook for list keys, or to target CSS selectors.

For example, you can use the useId() hook to generate a unique identifier for an HTML element so that it can be associated with aria-describedby attribute, like so:

import { useId } from 'react';

function PasswordField() {
  const passwordHintId = useId();
  // ...

  return (
    <>
      <input type="password" aria-describedby={passwordHintId} />
      <p id={passwordHintId}>
        The password should contain at least 18 characters
      </p>
    </>
  );
}

If you have multiple related elements, then you can use useId() to generate a shared prefix for them, as shown in the following example:

import { useId } from 'react';

function PasswordField() {
  const id = useId();
  // ...

  return (
    <>
      <label htmlFor={`${id}-passwordInput`}>Password:</label>
      <input
        type="password"
        id={`${id}-passwordInput`}
        aria-describedby={`${id}-passwordHint`}
      />
      <p id={`${id}-passwordHint`}>
        The password should contain at least 18 characters
      </p>
    </>
  );
}

Here, you can see that only one identifier is generated using useId(), which is differentiated using different suffixes (i.e. "-passwordInput" and "-passwordHint"). In this way, you can easily share the identifier with related elements.

If you are wondering why you can't simply hardcode a unique id, then the answer is that it's not a good practice because the component may be rendered more than once on the page:

function App() {
  return (
    <form>
      <h2>Choose password</h2>
      <PasswordField />
      <h2>Confirm password</h2>
      <PasswordField />
    </form>
  );
}

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.