Understanding How to Use the useId Hook in React 18
In React 18, several new hooks have been introduced, among many, the useId
hook which can be used for generating unique ids inside your components. To generate a unique ID, you can do the following:
import React, { useId } from 'react'
const Hooks = () => {
const id = useId() // Generates a random ID as a string, eg ":r1:"
return (
<React.Fragment>
<label htmlFor={id}>Check me</label>
<input type="checkbox" id={id} name="hook" />
</React.Fragment>
)
}
They are meant to be stable between the server and client-side, to avoid mismatches during hydration. It generates a string that includes a colon and is unique. This means you should avoid using it together with CSS.
They are also not meant to be used for unique keys in a list. For most cases, you can use the index of your array instead, or an ID returned from your database:
// π΄ Don't use useId for keys
const id = useId()
return posts.map(post => (
<article key={id}>
...
</article>
))
// π’ Do use indexes
return posts.map((post, index) => (
<article key={index}>
...
</article>
))
// π’ Do use ids returned from database
return posts.map(post => (
<article key={post.id}>
...
</article>
))
You can also use a single generate ID with multiple elements by simply prefixing or suffixing them as needed in the following way:
import React, { useId } from 'react'
const Hooks = () => {
const id = useId()
return (
<React.Fragment>
<label htmlFor={`email-${id}`}>Email</label>
<input type="text" id={`email-${id}`} name="email" />
<label htmlFor={`password-${id}`}>Password</label>
<input type="password" id={`password-${id}`} name="password" />
</React.Fragment>
)
}
When should you use the useId
hook?
- Use it for connecting two HTML elements together such as a label with an input
- Use it for places where you need a unique ID to be generated every time
- Use prefix or suffix for using the same generated ID over multiple times
When should you not use the useId
hook?
- Do not use the
useId
hook for CSS selectors - Do not use it for keys in a list
- Do not use it for values that should not change
Just like any other React hook, useId
can only be used in functional components, or a custom React hook function.
If you are interested in reading more about React hooks, seeing more examples for custom hooks, or just learning about the basics, make sure to check out the article below.
Rocket Launch Your Career
Speed up your learning progress with our mentorship program. Join as a mentee to unlock the full potential of Webtips and get a personalized learning experience by experts to master the following frontend technologies: