DEV Community

Cover image for Create a unique ID in React JS
Saleh Mubashar
Saleh Mubashar

Posted on Edited on

Create a unique ID in React JS

Hi Guys
Ok so in this post I will be giving you guys
the simple steps to create a unique reference
ID in react JS.
This has many uses such as giving a user uploaded
image a unique name for saving in a database.

Step 1:

Install UUID v4 using the following command



npm install uuidv4


ðŸ”ī Hot News: salehmubashar/create a unique id in react js f - āļŠāļĢāļļāļ›āļ”āļĢāļēāļĄāđˆāļēāļĨāđˆāļēāļŠāļļāļ” ðŸ”ī Hot News: salehmubashar/create a unique id in react js f - āļŠāļĢāļļāļ›āļ”āļĢāļēāļĄāđˆāļēāļĨāđˆāļēāļŠāļļāļ”

Step 2:

Import the package into your component, page or code etc.



import { v4 as uuid } from 'uuid';


ðŸ”ī Hot News: salehmubashar/create a unique id in react js f - āļŠāļĢāļļāļ›āļ”āļĢāļēāļĄāđˆāļēāļĨāđˆāļēāļŠāļļāļ” ðŸ”ī Hot News: salehmubashar/create a unique id in react js f - āļŠāļĢāļļāļ›āļ”āļĢāļēāļĄāđˆāļēāļĨāđˆāļēāļŠāļļāļ”

Step 3:

You can now assign the Uinique ID to any variable using the below code
unique_id is an example here, it can be any variable name.



const unique_id = uuid();


ðŸ”ī Hot News: salehmubashar/create a unique id in react js f - āļŠāļĢāļļāļ›āļ”āļĢāļēāļĄāđˆāļēāļĨāđˆāļēāļŠāļļāļ” ðŸ”ī Hot News: salehmubashar/create a unique id in react js f - āļŠāļĢāļļāļ›āļ”āļĢāļēāļĄāđˆāļēāļĨāđˆāļēāļŠāļļāļ”

And voila!, you're done.

Thank you all for reading this post.
If it was helpful, please consider following :)
Until next time
Bye!

Top comments (4)

ðŸ”ī Hot News: salehmubashar/create a unique id in react js f - āļŠāļĢāļļāļ›āļ”āļĢāļēāļĄāđˆāļēāļĨāđˆāļēāļŠāļļāļ”
 
felipebhz profile image
@FelipeBHZ • • Edited

If you are reading this in 2023, you should use the react-uuid package, otherwise you are going to get errors like:

Uncaught RangeError: Maximum call stack size exceeded
at Object.exports.deprecate (util.js:75:1)

ðŸ”ī Hot News: salehmubashar/create a unique id in react js f - āļŠāļĢāļļāļ›āļ”āļĢāļēāļĄāđˆāļēāļĨāđˆāļēāļŠāļļāļ”
 
salehmubashar profile image
Saleh Mubashar •

Thanks a lot for this!

ðŸ”ī Hot News: salehmubashar/create a unique id in react js f - āļŠāļĢāļļāļ›āļ”āļĢāļēāļĄāđˆāļēāļĨāđˆāļēāļŠāļļāļ”
 
catherineisonline profile image
Ekaterine Mitagvaria •

I am using it in React 18 and not having such errors. Besides, seems like react-uuid is deprecated right now.

ðŸ”ī Hot News: salehmubashar/create a unique id in react js f - āļŠāļĢāļļāļ›āļ”āļĢāļēāļĄāđˆāļēāļĨāđˆāļēāļŠāļļāļ”
 
luismartinezs profile image
Luis Martinez Suarez •

This has nothing to do with React