Code Snippets - uniqueId

Code Snippets - uniqueIdPhoto by
By Hemerson Carlin
2 min read

I recently had to remove underscore from a repository I was working on and I end up using some small tweaks with plain JS syntax instead. I have to say this is not the first time I do a similar job and I always use the same utility methods here and there.

For that reason, I'm gonna share some of those in my blog for future reference whenever I need one of them again.

It could be you came here for the same reason as me. We'd better share that knowledge 😉

uniqueId

Generates a unique global id for elements that need one.

Examples:

  • Setting key property when looping an array in ReactJS (watchout for potential performance issues if going this path!).
  • Setting id attribute to DOM elements.
  • Cache response from endpoints that don't provide you with an identifier.

As a , it keeps a local counter variable and for every new uniqueId generated counter's value is incremented. An optional prefix can also be sent in case you want some extra information alongside with the id.

function createUniqueId() {
  let counter = 0

  return (prefix = '') => {
    if (prefix) {
      return `${prefix}_${++counter}`
    }

    return `${++counter}`
  }
}

const uniqueId = createUniqueId()

console.log(uniqueId()) // 1
console.log(uniqueId()) // 2
console.log(uniqueId()) // 3
console.log(uniqueId('testing')) // testing_4

I hope that's helpful and interesting to you. 👋🏼

Did you know you can help me with this page?

If you see something wrong, think this page needs clarification, you found a typo or any other suggestion you might have feel free to open a PR and I will take care of the rest.

My entire site is available to edit on GitHub and all are very welcome 🤙🏼.

mersocarlin

Hemerson Carlin, also known as mersocarlin, is passionate and resourceful full-stack Software Engineer with 10+ years of experience focused on agile development, architecture and team building.

This is the space to share the things he likes, a couple of ideas and some of his work.

Previous Blog Posts