ReactJS - useId Hook



The useId is a react hook, which is introduced in the new version of React JS (18). It is used to generate unique IDs to pass for the accessibility features.

The useId() hook generates unique IDs that stay between re-renders. It ensures that produced IDs are unique throughout the React app and until the component that uses the ID is removed from the DOM. The generated ID will be changed if the component is re-inserted.

The useId() hook's primary function is to generate unique IDs for HTML form components. It makes it easier to generate unique IDs while constructing form inputs and labels in React.

Import

import { useId } from 'react';

To produce a unique ID we will call useId at the top level of our component. This hook does not have the parameter. And it returns the unique ID string associated with this useId call in the component.

How to use it?

The useId() hook is quite easy to use. Simply use const id = useId(); in the component code to call the hook.

Now check the below example, in which the useId hook is used to get a unique ID in the MyForm component and to connect the label and input tags.

function MyForm() {
   const id = useId();
   return (
      <>
         <label htmlFor={id}>User Name</label>
         <input id={id} type="text" placeholder={`Generated id is: ${id}`} />
      </>
   )
}

The id generated by the useId hook will be unique for the whole React application. It means no other element in our app will have the same id. This id will also remain the same as long as the component that uses it remains in the document object model (DOM) of the web page.

We can use the ‘useId’ in three different ways. First by creating distinct IDs for accessibility attributes, secondly by creating IDs for a number of related items and third by setting a common prefix for all generated IDs.

Examples

So we will discuss all these three ways one by one.

Example − Creating distinct IDs for accessibility attributes

Here is the example in which we have created a UsernameField component using the useId hook to generate distinct IDs for accessibility attributes −

import React from "react";
import { useId } from "react";

function UsernameField() {
   const usernameHintId = useId();
   
   return (
      <>
         <label>
            Username:
            <input type="text" aria-describedby={usernameHintId} />
         </label>
         <p id={usernameHintId}>
            Your username should be unique and contain only letters and numbers.
         </p>
      </>
   );
}

export default function App() {
   return (
      <>
         <h2>Create Account</h2>
            <UsernameField />
         <h2>Login</h2>
         <UsernameField />
      </>
   );
}

Output

create account

In this example, we have created a UsernameField component that uses the useId hook to generate a unique usernameHintId. This ID is used to link the input field to its matching hint message, allowing the component to be accessed. This component is then used again within the App component, showing how it can be reused with various IDs for different input fields.

Example − Creating IDs for a number of related items

If we want to assign IDs to numerous related items then we can use 'useId' which will build a common prefix for us −

To create unique IDs for the first name, last name, and email input fields within a form, we have three separate useId functions. Each input field and label has its own unique ID, giving proper accessibility and avoiding conflicts between the items.

import React from 'react';
import { useId } from 'react';

export default function App() {
   const firstNameId = useId();
   const lastNameId = useId();
   const emailId = useId();
   
   return (
      <form>
         <label htmlFor={firstNameId}>First Name:</label>
         <input id={firstNameId} type="text" />
         <hr />
         <label htmlFor={lastNameId}>Last Name:</label>
         <input id={lastNameId} type="text" />
         <hr />
         <label htmlFor={emailId}>Email:</label>
         <input id={emailId} type="email" />
      </form>
   );
}

Output

form

Example − Setting a common prefix for all generated IDs

Consider we are having many React applications running on the same web page. The useId hook can be used by each app to generate IDs for items such as input fields and labels. When we set up each app, we can define a unique "prefix" to ensure that the IDs from one app do not mistakenly match the IDs from another app.

index.js

import { createRoot } from 'react-dom/client';
import App from './App.js';
import './styles.css';

const root1 = createRoot(document.getElementById('root1'), {
   identifierPrefix: 'app1-'
});
root1.render(<App />);
const root2 = createRoot(document.getElementById('root2'), {
   identifierPrefix: 'app2-'
});
root2.render(<App />);

App.js

import { useId } from 'react';

function ColorPicker() {
   const colorId = useId();
   console.log('Generated identifier:', colorId);
   return (
      <>
      <label htmlFor={colorId}>Select Color:</label>
      <input type="color" id={colorId} />
      </>
   );
}

export default function App() {
   return (
      <>
         <h2>Choose a color</h2>
         <ColorPicker />
      </>
   );
}

index.html

<!DOCTYPE html>
<html>
   <head><title>My Color Picker App</title></head>
<body>
   <div id="root1"></div>
   <div id="root2"></div>
</body>
</html>

Output

choose color

In the above example, It has two different React apps. In this we have both the apps with its own identification prefix ("app1-" and "app2-"). This makes sure that, even with the fact that both apps use the same App component, the IDs provided by the useId hook do not conflict.

Limitations

The useId is a great tool that we can use in our React components, but it comes with limitations.

  • We should only use useId at the start of our component or in any custom tools we have created. It should not be used within loops or conditions. If we need to use it somewhere then we can create a new component and include the useId in it.

  • UseId should not be used to generate keys for lists. Instead, generate keys using the real data from our list. Keys assist React in keeping track of items in lists, and it is preferable to utilise real data for this.

reactjs_reference_api.htm
Advertisements