When developing with React, it's very common to make components like list by repeating the array form data.
However, we can usually see the warning if we set eslint.
β οΈ Missing "key" prop for element in iterator
It means that we don't pass the key property to the component in repeated process. Some developers grant index value to key property, but it causes another warning.
β οΈ Do not use Array index in keys
Why we don't do like this?
Why key should not be index
Unique key
First of all, if the index is used as the key value, each component cannot be properly identified.
For example, let's say that you have codes with values Bob, Joe, and Fred to form a list. React creates a DOM element for each individual and attaches the DOM element to that key. If the key is an index, each object could not actually be uniquely identified.
Specifically, when Bob is removed, Joe is now the first item and Fred is the second. In other words, the index number is difficult to be a unique key value because it can change when certain elements are removed.
Performance
Secondly, if the index value is given to the key, the performance may deteriorate when the array data is changed.
Even in the official React document, it is recommended not to put the Index value in the key value. There are three main reasons.
-
When you insert, delete, or rearrange items, the rendering order changes over time.
-
In addition to the index value, the case of generating values on the spot is similar.
-
The key is not actually delivered to the component and is used only in react.
URL:
https://yozm.wishket.com/magazine/detail/2634/
URL:
https://react.dev/learn/rendering-lists
URL:
https://www.reddit.com/r/react/comments/1daj9nz/whats_so_bad_about_index_as_key/


