What is useId in React?
useId
is a React hook introduced in React 18 that generates a unique, stable ID for use in accessibility attributes or for associating related elements in the DOM. It helps to prevent ID collisions in server-rendered and client-rendered content.
function Component() {
const firstNameId = useId();
const lastNameId = useId();
return (
<div>
<label htmlFor={firstNameId}>First Name</label>
<input id={firstNameId} type="text" />
<label htmlFor={lastNameId}>Last Name</label>
<input id={lastNameId} type="text" />
</div>
);
}