What is useId and when do you need it?

MediumHooksTheory Question

Hint

Generates stable unique IDs that are consistent between server and client — for accessibility attributes

Full Answer

useId generates a stable, unique ID that is consistent across server-side rendering and client-side hydration.

// ❌ Problem — random or Math.random IDs cause SSR hydration mismatch
function Field({ label }) {
  const id = Math.random(); // different value on server vs client → hydration error!
  return (
    <>
      <label htmlFor={id}>{label}</label>
      <input id={id} />
    
  );
}

// ✅ useId — stable, unique, SSR-safe
function Field({ label }) {
  const id = useId(); // e.g. ":r0:", ":r1:" — consistent server + client
  return (
    <>
      <label htmlFor={id}>{label}</label>
      <input id={id} />
    
  );
}

// Multiple IDs from one useId call — append suffixes
function ComboField() {
  const id = useId();
  return (
    <>
      <label htmlFor={`${id}-input`}>Name</label>
      <input id={`${id}-input`} aria-describedby={`${id}-hint`} />
      <p id={`${id}-hint`}>Your full name</p>
    
  );
}
💡 useId is purely for accessibility attributes (id, htmlFor, aria-*). Don't use it as a key prop in lists — use your data's actual IDs for those.

More Hooks Questions

Practice this in a timed sprint

5 free questions, no signup required