MyInternships.in

React Hooks

React useId Hook

useId generates a stable unique string that is identical on the server and the client. Its purpose is generating ids for accessibility attributes such as htmlFor, aria-describedby and aria-labelledby.


What is useId Hook in React?

useId generates a stable unique string that is identical on the server and the client. Its purpose is generating ids for accessibility attributes such as htmlFor, aria-describedby and aria-labelledby.

Why useId Hook matters

Hardcoded ids collide when a component is rendered more than once on a page, and Math.random() produces different values on server and client, causing hydration mismatches.

useId Hook example

Linking a label, input and hint
JSX
function PasswordField() {
  const id = useId();
  return (
    <>
      <label htmlFor={`${id}-pwd`}>Password</label>
      <input id={`${id}-pwd`} type="password" aria-describedby={`${id}-hint`} />
      <small id={`${id}-hint`}>At least 8 characters</small>
    </>
  );
}

How this works

One useId call provides a unique prefix; suffix it for each element that needs an id. Rendering the component ten times produces ten distinct, collision-free sets.

Key points to remember

  • It is for ids, not for list keys — it is not derived from your data.
  • Safe for server-side rendering, unlike random or counter-based ids.
  • Call it once per component and derive suffixes rather than calling it repeatedly.

Common mistakes with useId Hook

  • Using useId as a key in a mapped list.
  • Falling back to Math.random() for ids in a server-rendered app, which breaks hydration.

React useId Hook— Interview Questions & FAQs

Can I use useId to generate keys for a list?+

No. Keys must be derived from your data so they stay stable as the list changes. useId is only for DOM ids that link elements together for accessibility.

Related React Topics

Keep learning with these closely related lessons.

Ready to use your React skills?

Find verified React internships and fresher developer jobs across India.

Browse React Internships