Skip to main content
Practice Problems

What is useId hook in React?

What is useId?

useId is a React 18+ hook that generates unique, stable IDs that are consistent between server and client rendering. It's designed for linking HTML elements (e.g., form labels to inputs) without causing SSR hydration mismatches.


Basic Usage

tsx
import { useId } from "react"; function EmailInput() { const id = useId(); return ( <div> <label htmlFor={id}>Email:</label> <input id={id} type="email" /> </div> ); }

The Problem useId Solves

Without useId (SSR mismatch)

tsx
// ❌ Random IDs cause SSR hydration mismatch function Input({ label }: { label: string }) { const id = Math.random().toString(36); // Different on server and client! return ( <div> <label htmlFor={id}>{label}</label> <input id={id} /> </div> ); } // Warning: Prop `id` did not match. Server: "abc123" Client: "xyz789"

With useId (consistent)

tsx
// ✅ useId generates the same ID on server and client function Input({ label }: { label: string }) { const id = useId(); // Same value on server and client return ( <div> <label htmlFor={id}>{label}</label> <input id={id} /> </div> ); }

Multiple IDs from One Hook

tsx
function SignUpForm() { const id = useId(); return ( <form> <div> <label htmlFor={`${id}-name`}>Name:</label> <input id={`${id}-name`} /> </div> <div> <label htmlFor={`${id}-email`}>Email:</label> <input id={`${id}-email`} type="email" /> </div> <div> <label htmlFor={`${id}-password`}>Password:</label> <input id={`${id}-password`} type="password" /> </div> </form> ); }

ARIA Attributes

tsx
function Tooltip({ text, children }: { text: string; children: React.ReactNode }) { const id = useId(); return ( <div> <div aria-describedby={id}>{children}</div> <div role="tooltip" id={id}>{text}</div> </div> ); }

Important Rules

  • Do NOT use useId for list keys — use data-based keys instead
  • Do NOT use it for CSS selectors — the generated format (:r1:) is not CSS-safe
  • Call it at the top level of your component (standard hook rules)
  • Each call generates a unique ID within the component
tsx
// ❌ DON'T use useId for keys {items.map(item => <li key={useId()}>...</li>)} // WRONG! // ✅ Use data-based keys {items.map(item => <li key={item.id}>...</li>)}

Important:

useId generates SSR-safe unique IDs for accessibility attributes (htmlFor, aria-describedby, etc.). Use a single useId call with suffixes for multiple related IDs. Don't use it for list keys or CSS selectors.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.

Finished reading?
Practice Problems