Learn the useId Hook in React

useId is a React Hook for generating unique IDs.

I find this useful when you might reach for an extra library or code snippet to create a unique ID but don't want the extra overhead.

To get started with useId, you'll first need to call it at the top level of your component:

import { useId } from 'react';

function Example() {
  const myId = useId();
  // Rest of your component logic
}

It returns a unique ID string, specific to that particular useId call within that component.

Caveats

  • Being a Hook, useId must be called at the top level of your component or within custom Hooks. Avoid calling it inside loops, conditions, or nested functions.
  • If you need to use it within loops or conditions, consider refactoring by creating a new component.
  • Don't use it for generating keys in lists. Always derive keys from your data. 🦾
  • With server rendering, useId requires an identical component tree on the server and the client. If the trees you render on the server and the client don’t match exactly, the generated IDs won’t match.

Example

Here's how you can utilize the ID generated by useId:

import { useId } from 'react';

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

  return (
    <>
      <input type="password" aria-describedby={passwordHintId} />
      <p id={passwordHintId}>Your password hint goes here.</p>
    </>
  );
}

In the above example the unique ID is assigned to the aria-describedby attribute of the input field and the id of the paragraph element.


For more information, check out the docs here.

Reactjs
Avatar for Niall Maher

Written by Niall Maher

Founder of Codú - The web developer community! I've worked in nearly every corner of technology businesses: Lead Developer, Software Architect, Product Manager, CTO, and now happily a Founder.

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.