useId
Definition
`useId` is a React Hook for generating unique IDs that can be passed to accessibility attributes. It generates unique string IDs that are stable across server and client renders.
Explain Like I'm New
In HTML, if you click a `<label>`, it focuses the connected `<input>`. They connect using an ID: `<label htmlFor="name">` and `<input id="name">`. If you render this same component twice, you have two inputs with `id="name"`, which breaks HTML rules and accessibility. `useId` acts like a license plate generator, giving every single input a mathematically guaranteed unique ID, even if you render the component 100 times.
Real World Example
Building highly reusable form components (like a custom TextInput component) that are fully accessible (a11y) to screen readers. `useId` ensures the ARIA attributes and labels always match up correctly without you having to pass a manual ID prop.
Common Use Cases
- •Generating unique IDs for HTML forms (label htmlFor / input id)
- •Generating unique IDs for ARIA attributes (aria-describedby, aria-labelledby)
- •Preventing Hydration mismatches in SSR apps (like Next.js)
Interactive Example
Interview Questions
basic
- What problem does `useId` solve?
- Can you use `useId` to generate keys for lists (`.map()`)?
intermediate
- How does `useId` prevent SSR hydration mismatches?
- If you need an ID for an input AND an error message in the same component, should you call `useId` twice?
advanced
- What does the generated ID string actually look like under the hood?
- Can you use `useId` to query the DOM using `document.getElementById()`?
trick
- Does `useId` generate a random UUID like `Math.random()` or `Date.now()`?