Working with the useId() hook in React

Last updated on May 4, 2022 Pennywise Loading... Post a 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 topic page and Next.js topic page for the latest tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Related Articles