4

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?

Mel
  • 625
  • 9
  • 25
  • 3
    If you need it to persist through page refresh then you'll need to store it somewhere. Storing it in a database is the best way to guarantee it will stick around. But you might look into using local storage or a cookie if you can't use a backend service. Also, see https://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid for how to generate an ID that is likely to be unique. – Rich McCluskey Dec 02 '20 at 00:01
  • @RichMcCluskey I just need it as a temporary way to identify a client during the account creation process, I plan to store it with Context once I figure a way to create a unique id that won't change on refresh. – Mel Dec 02 '20 at 00:11
  • Thanks for the link, I was already looking in the wrong direction with Math.random() – Mel Dec 02 '20 at 00:14
  • In case you need it. https://www.npmjs.com/package/uuid – jtabuloc Dec 02 '20 at 02:30
  • If you want a unique ID that is guaranteed to be unique across clients, you should both generate and store that ID on the server side, not client. – jered Dec 02 '20 at 03:02

2 Answers2

3

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.

jtabuloc
  • 2,479
  • 2
  • 17
  • 33
2

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.

Maxim Mazurok
  • 3,856
  • 2
  • 22
  • 37
  • 1
    This is a good solution that I might end up using for my future projects, thanks – Mel Dec 02 '20 at 09:39