React.js Keys - React Keys

While working with arrays in react.js, it's very important to handle keys to avoid unnecessay re-redenring of DOM Element while reconciliation.

Let's understand by the following example:

let fruits = [{ id: 12, name: "apple" }, { id: 11, name: "banana" }, { id: 10, name: "grapes" }]
    { fruits.map((fruit, i) => (
  • {fruit.name}
  • )) }
  • apple
  • banana
  • grapes

When any changes occurs in the fruits array, a new list of fruit component objects are created. The React reconcilerwill compare the newly created objects with the current versions it has in the DOM. If any differences are detected between certain properties, it will redraw the components believing that it's the same object, but properties have changed.

let fruits = [{ id: 13, name: "orange" }, { id: 12, name: "apple" }, { id: 11, name: "banana" }, { id: 10, name: "grapes" }]
    { fruits.map((fruit, i) => (
  • {fruit.name}
  • )) }
  • orange
  • apple
  • banana
  • grapes

As In our case we are using array index position as it's key, so when a new item will add/remove from the array items keys will again changed so React reconciler noticing that the keys do not match their previous properties!

We can prevent this by like following

Where possible you should always use some sort of primary key from the data object.
let fruits = [{ id: 13, name: "orange" }, { id: 12, name: "apple" }, { id: 11, name: "banana" }, { id: 10, name: "grapes" }]
    { fruits.map((fruit, i) => (
  • {fruit.name}
  • )) }
  • orange
  • apple
  • banana
  • grapes
Significance of keys:
  1. In some case, it is possible that performance impact may be minimal.
  2. It will be noticeable with very large arrays that get sorted/re-ordered as it will reduce the need for a majority of your list to be rendered.
Important Tips:
  1. Make sure every item in the list has a unique key.
  2. Never use unstable keys like Math.random() to generate a key.
  3. It is prefered to not use indexes as a key unless you know for sure that the list is a static list (no additions/re-ordering/removal to the list).
  4. React will run into performance degradation and unexpected behaviour if unstable keys are used.