Last updated: Apr 7, 2024
Reading timeยท4 min
useId
hook to generate a unique ID for an input fieldlodash/uniqueId
package to generate a unique IDInstall 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.
# 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
You can import and use the module as follows.
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;
The uuid module creates random UUIDs.
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.
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;
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.
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;
The same approach can be used if you need to generate a unique ID for input fields.
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;
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.
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.
useId
hook to generate a unique ID for an input fieldYou can also use the native useId hook to generate a unique ID for an input field.
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 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.
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;
Note that you shouldn't use the useId
hook to generate values for the
key prop of list
elements.
lodash/uniqueId
package to generate a unique IDYou can also use the lodash/uniqueId package to generate a unique ID in React.
Install the module by running the following command.
# 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.
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;
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.
You can learn more about the related topics by checking out the following tutorials: