useId

⭐ Interview Importance: MEDIUM
⏱️ Revision Time: 2 min

useId

useId is a React Hook that generates unique IDs that can be passed to accessibility attributes. It was introduced in React 18.

Syntax

const id = useId()

Why use useId?

When writing accessible HTML forms, you need to connect <label> elements to their corresponding <input> elements using the for (or htmlFor in JSX) and id attributes.

<label htmlFor="password-input">Password:</label>
<input id="password-input" type="password" />

If you hardcode the ID "password-input" inside a reusable PasswordField component, and then render that component twice on the same screen, you will have duplicate IDs in the DOM. This breaks accessibility (screen readers won’t know which label belongs to which input) and violates HTML spec.

Before useId, developers often used Math.random() or libraries like uuid to generate IDs. However, generating random IDs on the fly causes severe issues with Server-Side Rendering (SSR) because the ID generated on the server will not match the ID generated during hydration on the client.

useId solves both problems:

  1. It guarantees uniqueness across the entire application.
  2. It generates exactly the same ID on the server and the client during hydration.

Usage Example

import { useId } from 'react';

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

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

Generating Multiple IDs in One Component

If you have a complex component with multiple inputs, you don’t need to call useId multiple times. You can call it once and append prefixes or suffixes to it.

import { useId } from 'react';

function NameFields() {
  const id = useId();

  return (
    <div>
      <label htmlFor={id + '-firstName'}>First Name</label>
      <input id={id + '-firstName'} type="text" />
      
      <label htmlFor={id + '-lastName'}>Last Name</label>
      <input id={id + '-lastName'} type="text" />
    </div>
  );
}

What NOT to do

Do not use useId to generate keys for lists.

Keys should be stable identifiers generated from your data (like a database ID). useId is strictly for generating accessible DOM IDs.

Interview Questions

Q: What is useId primarily used for?
A: It generates unique, stable string IDs. It is critical for accessibility (e.g., linking a <label htmlFor={id}> to an <input id={id}>) ensuring that the generated ID matches perfectly between the Server-Side Render and the Client-Side Hydration.

Q: Should you use useId to generate key props for a mapped list?
A: No. Keys must be tied to your actual data (like a database ID). useId is strictly for generating stable DOM accessibility IDs, not for React reconciliation.