0 day streak
javascript / intermediate
Snippet

Generating Unique IDs with useId

useId is a hook for generating unique IDs that are stable across server-side rendering and client-side hydration. It is primarily used to link labels and inputs for accessibility.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function LoginForm() {
const id = React.useId();
return (
<form>
<div>
<label htmlFor={id + '-user'}>Username</label>
<input id={id + '-user'} type="text" />
</div>
<div>
<label htmlFor={id + '-pass'}>Password</label>
<input id={id + '-pass'} type="password" />
</div>
</form>
);
}
react
Breakdown
1
const id = React.useId();
Creates a unique, stable prefix for IDs within this component instance.
2
htmlFor={id + '-user'}
Links the label to the input field, ensuring assistive technologies can identify the association.