React useId Hook

The useId hook is a React Hook for generating unique IDs that can be passed to accessibility attributes. It ensures that IDs are stable across server-side rendering and client-side hydration, preventing hydration mismatches.

Why use useId?

In traditional HTML, we use id and for attributes to link labels to inputs. However, hardcoding IDs in components can lead to duplicate IDs if the component is rendered multiple times on the same page. useId solves this by generating a unique ID for every instance of the component.

Syntax

JavaScript

import { useId } from 'react';

function MyInput() {
  const id = useId();
  return (
    <div>
      <label htmlFor={id}>Email:</label>
      <input id={id} type="email" />
    </div>
  );
}          

Using useId for Multiple Elements

If you need unique IDs for multiple related elements in the same component, you can use the same base ID generated by useId and append a suffix.

JavaScript

function PasswordField() {
  const id = useId();
  return (
    <>
      <label htmlFor={id + '-pass'}>Password:</label>
      <input id={id + '-pass'} type="password" />
      <p id={id + '-hint'}>Must be 8 characters long.</p>
    </>
  );
}          

Note:useId should not be used to generate keys in a list. Keys should be generated from your data.

Key Benefits