Generate a unique id in react that persist

Viewed 2929

I need to keep a unique identifier for each client using my react app.

doing this will regenerate a random string (what I want) but does this on each refresh which is not what I want

  const [id] = useState(Math.random().toString(36).substr(2, 8));

I've found uniqueId() form lodash but I'm afraid the id's won't be unique across multiple clients as it only give a unique Id and increment it at every call (1, 2, 3...)

  const [id] = useState(_uniqueId());

Is there some kind of _uniqueId that generates a random string and also persist through page refresh?

2 Answers

I don't think there is a built-in or out-of-the-box solution that generates unique id in react that persist automatically. You have two problems to solve.

  • How to generate unique id. Which was already solved by using the uuid.
  • And how to persist it.

There are plenty of storage you can use depend on your need. Here's few of them where you can persist your data assuming you want it to be stored in client side.

Again, it depends on your use case. So, carefully check them out which one fits on your requirement.

Another way to generate a temporary ID that would be the same for the same client, without storing it is to use browser fingerprinting.

For example, you can take user-agent, client timezone, and screen resolution, apply some hash function to them and call it an ID.

There are more advanced ways of fingerprinting that would result in less chance of two different users having the same ID, but it'll never be a 0% chance.

You also might want to use some libraries, such as https://github.com/fingerprintjs/fingerprintjs for this.

Related