What is the useId hook for, and why not use Math.random for IDs?
useId generates a stable unique ID that matches between server and client renders. It is meant for linking labels to inputs and aria attributes. Math.random changes each render and differs on the server, causing hydration mismatches.
Explain it simply
A label and its input must share an id so that clicking the label focuses the field and screen readers announce it correctly. If the component is used twice on the page, hard-coded IDs collide.
Math.random() or a counter looks tempting but fails. The server produces one number, the browser produces another during hydration, and React warns about a mismatch. Random values also change every render, which breaks the link.
useId returns a string like :r1: that is the same on server and client and unique per call site.
Example
function Field({ label }) {
const id = useId();
return (
<>
<label htmlFor={id}>{label}</label>
<input id={id} />
</>
);
}
// Two <Field /> on one page get two different idsDo not use useId to generate list keys; keys should come from your data.
What to say in the interview
"useId produces a unique, stable ID that is consistent across server and client rendering. I use it to connect labels, inputs and aria attributes in reusable components. Math.random or incrementing counters cause hydration mismatches and change on re-render. It is not for list keys."
Common mistakes
- Using useId output as a key in a list.