Warning: Each child in a list should have a unique “key” prop

The issue:

When we were developing the react.js based app we got in the following issue:

Warning: Each child in a list should have a unique "key" prop

The reason of the issue:

When we design components in react.js we always think about the reusability of the component. But when we render the same HTML block multiple times then react.js complains about not having a unique key.

As we all know that react creates a virtual DOM and it only renders the part of the DOM that has been changed. To do that react needs unique key for all possible blocks. So, if we can assign a unique ID to a repetitive block, then the issue will be solved.

The solution:

In our case we were looping on a repetitive block. But as soon as we added a unique ID like below the issue was resolved:

{items.map((item, i) => <Card key={item.uniqueId} item={item}/>)}

What should be the value of the key?

As this key is used by react to detect the DOM changes, it should have the following value:

  • Unique: A key cannot be identical to that of a sibling component. It should be unique to the entire DOM.
  • Static: A key should not ever change between renders. The dynamic value will degrade the performance.

Why random number as key is not good?

{items.map((item, i) => <Card key={Math.random()} item={item}/>)} // Bad approach

If we use the random numbers as a key, it will always force react to re-render each item in the list, even when it is not required.

This approach is not good because it degrades the performance as Math.random() will cause many component instances and DOM nodes to be unnecessarily recreated.

Reference: