The impacts of using index as key in React

Let's say there's a list that you want to show in React, and some developers may use index as key to avoid the warning of React, like this:

    {list.map((item, index) =>
  • {item.name}
  • )}

Sure, you can do that, but it's a bad idea. Let's see what official said:

We don’t recommend using indexes for keys if the order of items may change. This can negatively impact performance and may cause issues with component state.

But how does the key work? Don't worry, this is what I want to talk about next.

Example

Let's start with a example to figure out what the difference between using index and using unique id.

Here is the example.

we render 2 different list initially and every item has a uncontrollable input. There are also some buttons on top which we can insert or delete items, each new item will be colored.

  • push: insert a item at the end of list
  • unshift: insert a item at the start of list
  • spliceInsert: insert a item at the middle of list

The left side represents list with index-key, the right side represents list with unique-key.

The impacts of using index as key in React_第1张图片
The impacts of using index as key in React_第2张图片

As we can see from pictures, there seems to be something wrong on the left side. It got confused about which item belonged to which dom.

Analyze

It will reuse the dom that already exist if their key are the same, that's the role of key. For more detail, here is the source code.

For the sake of understanding, I'll explain it in a case.

An array of length 5, I want to insert an item in 3rd position. when it comes to index of [0, 1], it's okay to reuse the existing doms. But when it comes to index of 2, it also reuses the existing dom because of same key. Besides, their state is different so the children of dom[2] will be updated. Next, index of 3 reuses dom[4] and so on.

It may cause terrible performance if list is long enough. If you insert a item at the start of list, it'll insert a dom at the end and update children all of item. But with unique id, it just insert a dom at the start.

Conclusion

It's a bad idea to use the array index since it doesn't uniquely identify your elements. In cases where the array is sorted or an element is added to the beginning of the array, the index will be changed even though the element representing that index may be the same. This results in unnecessary renders.

If you have to use index as key, please make sure you only operate the last item.

你可能感兴趣的:(react.js,javascript)