Do Not Use Index As A Key
A key is a unique and permanent property that allows you to identify changed, updated, or deleted items from a list of elements. In React anything that you are returning from inside the map () function must have a key.
const mappedFruit = fruits.map(( fruit) => {
return ( <li key= {fruit.id} name={fuit.name}></> )
});
The Key gives each element an identity in an array for React to know which elements have been updated. React uses the keys to figure out the differences between two lists by matching them. This process is called reconciliation. Keys do not need to be unique globally just unique for the list of elements. This means you can have multiple lists with the same key in an application.
When an array does not have an ID already you may want to use the index (the position in the list) as the key. Don't. Even though it will work for simple applications using the index as a key is frowned upon. Robin Pokorny says the only time it is safe to use the index as a key is when the situation hits these three points. First, the list and the items are static. This means they are not computed and do not change. Second, the items in the list have no IDs. Finally, the list is never reordered or filtered.
The problem is in the reordering of the array. If the key is the index it will confuse React and possibly render the wrong item.
<li key={0}>apples</>
<li key={1}>oranges</>
<li key={2}>bananas</>
<li key={3}>pears</>
In the example, we have our list of fruit. Say we want to add peaches. The peaches will be added to the top of the list and the index can change.
<li key={0}>peaches</>
<li key={1}>apples</>
<li key={2}>oranges</>
<li key={3}>bananas</>
<li key={4}>pears</>
Using IDs as the key allows the key to be stable. If the list generated has no IDs, create them on time of the data being received.
sources : https://robinpokorny.com/blog/index-as-a-key-is-an-anti-pattern/
https://www.geeksforgeeks.org/reactjs-keys/
https://medium.com/swlh/understanding-the-importance-of-the-key-prop-in-react-f2b92ce65f45
https://sipodsoftware.com/definitive-guide-to-react-key-prop/
Subscribe to my newsletter
Read articles from Shawn Conway directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by