- Published on
React's useId Hook
The useId
hook, which was introduced in React 18, simplifies the process of creating unique IDs for your React components. These IDs are very important for form processing, accessibility, and different UI operations. Let's explore the potential of useId with simple descriptions, useful examples.
Using useId
Import: Begin by importing useId from the react library:
import { useId } from 'react'
Hook Call: Employ useId within your functional component:
function MyComponent() { const uniqueId = useId() // ... (use uniqueId in JSX) }
Simple Form Fields
Let's start with a straightforward example. Imagine you’re building a login form with email and password fields. Instead of hardcoding IDs, we’ll use useId
to generate unique ones:
import React from 'react'
function LoginForm() {
const emailId = useId()
const passwordId = useId()
return (
<form>
<div>
<label htmlFor={emailId}>Email</label>
<input id={emailId} type="text" placeholder="Your email" />
</div>
<div>
<label htmlFor={passwordId}>Password</label>
<input id={passwordId} type="password" placeholder="Your password" />
</div>
</form>
)
}
export default LoginForm
n this example, useId
generates unique IDs for both the email
and password
fields. Even if LoginForm
appears multiple times on the screen, the generated IDs won't clash.
Dynamic List Rendering
Suppose you’re building a list of items, and each item needs a unique key. useId simplifies this process:
import React from 'react'
function ItemList({ items }) {
return (
<ul>
{items.map((item) => (
<li key={useId()}>{item}</li>
))}
</ul>
)
}
export default ItemList
Here, each list item gets a unique key generated by useId. No more worrying about manual key management!
Custom Prefix
Sometimes you want to add a custom prefix to your IDs. Maybe you’re building a reusable component. useId allows you to specify a shared prefix:
import React from 'react'
function CustomComponent() {
const customId = useId('my-prefix')
return <div id={customId}>Custom content</div>
}
export default CustomComponent
The generated ID will look something like my-prefix-123
.
Conclusion
React 18's useId hook makes it simple to create unique IDs that improve your components' maintainability and accessibility. By understanding of its fundamental features, limitations, and optimal approaches, you'll have the necessary knowledge to utilize this powerful tool.