useId is a built-in hook that is available since React 18. The purpose of the hook is for generating unique IDs that are stable across the server and client while avoiding hydration mismatches.
Important points to keep in mind about the useId hook:
- useId returns a string that includes colons (:), e.g., :r0:, :r1:, etc. This string is NOT supported in CSS selectors.
- You should NOT use the useId hook to generate keys for items in a list (use your data instead).
- Just like other hooks, make sure you only use the useId hook in functional components.
Table of Contents
Example
The code:
import { useId } from 'react'
function App() {
const id = useId();
return (
<form>
<div>
<label htmlFor={`email-${id}`}>Email</label>
<input id={`email-${id}`} type="text" placeholder='Your email' />
</div>
<div>
<label htmlFor={`password-${id}`}>Password</label>
<input id={`password-${id}`} type="password" placeholder='Your password' />
</div>
</form>
);
}
export default App;
Screenshot:
References
- Hooks API Reference (reactjs.org)
- React releases (github.com)
Conclusion
We’ve covered almost everything you need to know about a new hook called useId in React. This is a convenient tool for component libraries integrating with accessibility APIs that require unique IDs. If you’d like to explore more useful and interesting things in the modern React world, take a look at the following articles:
- React: Get the Position (X & Y) of an Element
- React + TypeScript: Making a Reading Progress Indicator
- React Router: How to Highlight Active Link
- React + TypeScript: Re-render a Component on Window Resize
- React Router Dom: Implement a Not Found (404) Route
- React + TypeScript: Handle onCopy, onCut, and onPaste events
You can also check our React category page and React Native category page for the latest tutorials and examples.