How to generate unique IDs in React.js [3 Ways]

avatar
Borislav Hadzhiev

Last updated: Apr 7, 2024
4 min

banner

# Table of Contents

  1. How to generate unique IDs in React.js
  2. Generating unique IDs for input fields in React.js
  3. Using the native useId hook to generate a unique ID for an input field
  4. Using the lodash/uniqueId package to generate a unique ID

# How to generate unique IDs in React.js

Install and use the uuid module to generate unique IDs in a React.js application.

You can use the uuidv4() method in the body of your function components or directly in the JSX code.

Open your terminal in your project's root directory (where your package.json file is) and run the following command.

shell
# with NPM npm install uuid # with YARN yarn add uuid # -------------------------------- # Install the typings if you use TypeScript # with NPM npm install @types/uuid --save-dev # with YARN yarn add @types/uuid --dev

install uuid module

You can import and use the module as follows.

App.js
import React from 'react'; import {v4 as uuidv4} from 'uuid'; function App() { console.log(uuidv4()); return ( <div style={{margin: 50}}> <h2>bobbyhadz.com</h2> <h2>{uuidv4()}</h2> <h2>{uuidv4()}</h2> </div> ); } export default App;

generated unique ids

The code for this article is available on GitHub

The uuid module creates random UUIDs.

App.js
import {v4 as uuidv4} from 'uuid'; // d4a974b4-24cf-49ab-90a2-229758ea922d console.log(uuidv4())

If you need to set a prefix for the unique ID, use a template literal.

App.js
import React from 'react'; import {v4 as uuidv4} from 'uuid'; function App() { console.log(`my-unique-${uuidv4()}`); return ( <div style={{margin: 50}}> <h2>bobbyhadz.com</h2> <h2>{`my-unique-${uuidv4()}`}</h2> <h2>{`my-unique-${uuidv4()}`}</h2> </div> ); } export default App;

generate random uuid with prefix

I've written a detailed guide on how to concatenate strings and variables in React.

You can also use the uuid module to generate version 1 (timestamp) UUIDs.

App.js
import React from 'react'; import {v1 as uuidv1, v4 as uuidv4} from 'uuid'; function App() { console.log(uuidv1()); console.log(uuidv4()); return ( <div style={{margin: 50}}> <h2>bobbyhadz.com</h2> <h2>{uuidv1()}</h2> <h2>{uuidv4()}</h2> </div> ); } export default App;

generate v1 timestamp uuid

The code for this article is available on GitHub

# Generating unique IDs for input fields in React.js

The same approach can be used if you need to generate a unique ID for input fields.

App.js
import React from 'react'; import {useState} from 'react'; import {v4 as uuidv4} from 'uuid'; function App() { const [messageId] = useState( `message-${uuidv4()}`, ); return ( <div style={{margin: 50}}> <h2>bobbyhadz.com</h2> <div> <label htmlFor={messageId}>Your message: </label> <input id={messageId} name="message" type="text" /> </div> </div> ); } export default App;

generating unique ids for input fields

The code for this article is available on GitHub

We used the useState hook to store the generated ID in the state.

The hook can be passed an initial value.

The messageId variable stores the unique ID.

Usually 2 values are destructured from the useState hook - the state variable and the setState() function.

App.js
const [messageId, setMessageId] = useState( `message-${uuidv4()}`, );

However, we won't be changing the id prop of the input field so the function is not needed.

# Using the native useId hook to generate a unique ID for an input field

You can also use the native useId hook to generate a unique ID for an input field.

App.js
import React from 'react'; import {useId} from 'react'; function App() { const messageId = useId(); console.log(messageId); // ๐Ÿ‘‰๏ธ :r0: return ( <div style={{margin: 50}}> <h2>bobbyhadz.com</h2> <div> <label htmlFor={messageId}>Your message: </label> <input id={messageId} name="message" type="text" /> </div> </div> ); } export default App;
The code for this article is available on GitHub

The useId hook is used to generate unique IDs that can be passed to accessibility attributes.

The useId hook does not take any parameters.

One thing to note when using this approach is that you might run into issues if you have to use the document.querySelector method.

The hook creates unique IDs formatted as :r0: and selectors starting with a colon are not valid.

If you need to prefix the unique ID with a value, use a template literal.

App.js
import React from 'react'; import {useId} from 'react'; function App() { const messageId = `message${useId()}`; console.log(messageId); // ๐Ÿ‘‰๏ธ message:r0: return ( <div style={{margin: 50}}> <h2>bobbyhadz.com</h2> <div> <label htmlFor={messageId}>Your message: </label> <input id={messageId} name="message" type="text" /> </div> </div> ); } export default App;
The code for this article is available on GitHub

Note that you shouldn't use the useId hook to generate values for the key prop of list elements.

# Using the lodash/uniqueId package to generate a unique ID

You can also use the lodash/uniqueId package to generate a unique ID in React.

Install the module by running the following command.

shell
# with NPM npm install lodash.uniqueid # with YARN yarn add lodash.uniqueid # -------------------------------- # Install the typings if you use TypeScript # with NPM npm install @types/lodash.uniqueid --save-dev # with YARN yarn add @types/lodash.uniqueid --dev

Then import and use the module as follows.

App.js
import React, {useState} from 'react'; import uniqueId from 'lodash/uniqueId'; function App() { const [messageId] = useState(uniqueId('message-')); console.log(messageId); // ๐Ÿ‘‰๏ธ message-1 return ( <div style={{margin: 50}}> <h2>bobbyhadz.com</h2> <div> <label htmlFor={messageId}>Your message: </label> <input id={messageId} name="message" type="text" /> </div> </div> ); } export default App;

using lodash unique id package to generate unique id

The code for this article is available on GitHub

The uniqueId function generates unique IDs starting at 1.

You can pass an optional prefix to the function.

I've also written an article on how to generate a random number in React.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev