0

What is the significance of keys in React? I read that using the index in the loop is not the best solution for keys. Why?

Aleksandr Golovatyi
  • 1,033
  • 1
  • 11
  • 18
  • just google it, there are a lot of articles out there which tell you why it is not good to use it: [first result on google](https://medium.com/@robinpokorny/index-as-a-key-is-an-anti-pattern-e0349aece318) – Dominik Apr 11 '18 at 15:04
  • I think this question is too broad. I think you should reframe your question and try to explain what doesn't make sense about keys. Otherwise you are just attracting answers that regurgitate the documentation to you (which you are getting). You need to give context about what you don't understand. – zero298 Apr 11 '18 at 15:07

2 Answers2

5

React uses keys to give an "identity" to each React element you render. When two elements have they same key, they're treated as the same element, otherwise, they're different. This helps when elements are rearranged in lists, or moved to different locations within the render function, so React can perform efficient DOM manipulations to achieve the end result you want. See the docs for more info.

I read that using the index in the loop is not the best solution for keys. Why?

Because it's the same as not giving keys to the list items at all. If you had a list like [a, b, c] then you remove the one in the middle, [a, c], if they were all keyed by index, React would think you just removed the last one, instead of the one in the middle.

kingdaro
  • 11,528
  • 3
  • 34
  • 38
  • 1
    This is correct. The only use case where the array index could be used as the key is if you are sure you will only ever append items to the array and never remove items (except the last one) during the lifetime of the component which is obv a very limited one. – trixn Apr 11 '18 at 15:30
1

Keys help React identify which items have changed, are added, or are removed. Keys should be given to the elements inside the array to give the elements a stable identity:

From: React Documentation - Lists and Keys

If the key is an index, moving an item changes it. As a result, component state for things like uncontrolled inputs can get mixed up and updated in unexpected ways.

From: React Documentation - Reconciliation

Vlad274
  • 6,514
  • 2
  • 32
  • 44