Say you. Say me. Say it together. UseId.
Table of Contents
The basics
useId is pretty much all basics. It doesn't take any arguments.
const id = useId();
It's just an easy way of generating a random, unique ID for an element.
Why? Well, there's a few benefits:
useIdavoids collisions by default. Even if a component is rendered multiple times on the same page,useIdensures that all of the components have unique ID attributes.- Enables server-side rendering consistency.
useIdcreates an ID on the server. Then during client hydration, it will use the same ID, preventing hydration errors.
Here's a real-world example
Here, we generate IDs for each input, and the form itself, using useId.
Then we can use the generated IDs for both the inputs and the input labels, to ensure they are always consistent with one another.
const FormComponent = () => {
const formID = useId();
const nameInputID = useId();
const emailInputID = useId();
return (
<form action="" id={formID}>
<label htmlFor={nameInputID}>Name:</label>
<input type="text" name="name" id={nameInputID} />
<label htmlFor={emailInputID}>Email:</label>
<input type="email" name="" id={emailInputID} />
</form>
)
};
Here's the benefit, if we render that component multiple times, each instance will have its own set of unique IDs, which avoids having invalid HTML due to repeated element IDs:
<form action="" id="_S_1_">
<label for="_S_2_">Name:</label>
<input id="_S_2_" type="text" name="name">
<label for="_S_3_">Email:</label>
<input id="_S_3_" type="email" name="">
</form>
<form action="" id="_S_4_">
<label for="_S_5_">Name:</label>
<input id="_S_5_" type="text" name="name">
<label for="_S_6_">Email:</label>
<input id="_S_6_" type="email" name="">
</form>
If we used hard-coded idattributes on the component, if we were to re-use the same component multiple times on the page, we'd have repeated element IDs.