Working with the useId() hook in React

Updated: March 3, 2023 By: Pennywise One comment

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.

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

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:

You can also check our React category page and React Native category page for the latest tutorials and examples.

Subscribe
Notify of
guest
1 Comment
Inline Feedbacks
View all comments
bob
bob
1 year ago

great!

Related Articles