Skip to content

useId Hook

useId generates stable unique IDs that work with server-side rendering and hydration. Use it to connect <label htmlFor> with <input id>, aria-labelledby, and other accessibility attributes.

Stable IDs Across Server and Client

Before useId, developers used incrementing counters or Math.random() for IDs — both break SSR hydration or uniqueness guarantees. useId produces consistent IDs per component instance across server and client.

Do not use useId for list keys. Keys should come from your data. useId is for accessibility wiring within one component instance.

function EmailField() {
  const id = useId();
  return (
    <>
      <label htmlFor={id}>Email</label>
      <input id={id} type="email" aria-describedby={`${id}-hint`} />
      <p id={`${id}-hint`}>We'll never share your email.</p>
    </>
  );
}

One useId call can prefix multiple related element IDs.

useId Usage

const id = useId();           // ":r1:" style string
<label htmlFor={id}>
<input id={id} />
  • Call once per component instance needing IDs.
  • IDs include colons — valid in HTML5 but escape in CSS selectors.
  • Not for key props in lists.
  • Available in React 18+.

useId Reference

When to use useId vs alternatives.

Use Case Solution
Label + input link useId() for id/htmlFor
aria-describedby ${id}-error pattern
SSR-safe IDs useId (not Math.random)
List item keys Data id, NOT useId
Multiple fields One useId, suffix per field

useId and Server Components

In SSR and frameworks like Next.js, useId ensures hydration matches server-rendered IDs. Random client-only IDs cause hydration mismatch warnings.

IDs with Colons in CSS

Generated IDs like :r0: must be escaped in CSS selectors (#\:r0\:). Prefer associating via htmlFor/id rather than styling by generated id.

Common Mistakes

  • Using useId for list keys.
  • Calling useId inside loops (breaks hook rules).
  • Using Math.random() for ids in SSR apps.
  • Generating separate useId per related field when suffixes suffice.

Key Takeaways

  • useId generates SSR-safe unique IDs.
  • Primary use: accessibility associations (label, aria).
  • Not a replacement for list keys from data.
  • Prefix/suffix pattern links multiple related elements.

Pro Tip

Combine useId with form libraries — many accept id props for accessible error message linking.