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:

<ul>
  {list.map((item, index) =>
    <li key={index}>{item.name}</li>
  )}
</ul>

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.

dom confused
text confused

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值