ReactJS

React: Unique Keys in Arrays

According to ReactJS, each child in an array should have a unique “key” prop.

Why?

How?


The WHY

Several reasons:

  1. First, as React kept reminding us, performance reasons: because React relies on heuristics, if the assumptions behind them are not met, performance will suffer [1].
  2. Then there’s the identity reason [2], for instance, in arrays that support re-ordering. Which means we can’t just assign something like Math.random() or simply the index within array as key, since they won’t constitute stable identities.

The HOW

When our data comes from backend, unique IDs are usually dealt with snuggly. Now we’re going to create a simple simulation on the frontend.

Since in most cases, reordering is a pretty normal expectation when rendering array elements, the requirements for our Key Prop would include:

  • stable, not random, not just element index
  • nothing that can potentially be a duplicate, like milliseconds or randomly generated colour keys

In order to keep track of anonymously assigned data, closure comes in very handy.

const createUniKeyFor = (function(){
  let obj = {};

  return function(keyword) {
    obj[keyword] = (keyword in obj) ? (++obj[keyword]) : 0;
    return keyword + '_' + obj[keyword];
  };
})();

So to get unique IDs when creating todo items, simply call:

const key = createUniKeyFor('todoitem');
// returns: todoitem_0, todoitem_1...

And if we want unique keys for another item, we could just use another keyword when calling the function. It will privately and neatly keep track of them for you.

Standard