This site runs best with JavaScript enabled.useId React Hook

useId React Hook

Photo by No Revisions

useId hook usage example

useId hook helps in generating unique IDs on both the client and server

The id is unique to each component, so no worrying about duplicates if we render the form multiple times on the same page

The id generated is something like this :r1:

For performance’s sake, we should use the useId hook once in the component

The ids for different elements will be something like :r1:-email, :r1:-name

This hook is very useful when it comes to server side rendering because it helps to avoid the mismatch of ids on server and client

1import React, {Fragment, useId} from 'react'
3function SignUpForm() {
4 const id = useId()
5 return (
6 <Fragment>
7 <div>
8 <label htmlFor={`${id}-email`}>Email</label>
9 <input id={`${id}-email`} type="email" />
10 </div>
11 <div>
12 <label htmlFor={`${id}-name`}>name</label>
13 <input id={`${id}-name`} type="name" />
14 </div>
15 </Fragment>
16 )
19export default SignUpForm
Share article
James Chege

James Chege is a software developer in Nairobi