Suppose I have this array:
[
{ label: 'Something', value: 4815 },
{ label: 'Another', value: 1623 },
{ label: 'Else', value: 4248 },
{ label: 'Whatever', value: 1516 },
{ label: 'Something', value: 2342 },
{ label: 'Yep', value: 4815 }
]
If I do arr.map(item => (<div key={item.label}>...</div>)) then the key will be repeated. I know the ideal scenario would be that the data has ids, but supposing it doesn't have, is it a good idea to do something like:
arr.map((item, index) => (<div key={`${item.label}-${index}`}>...</div>))
It is not recommended if the order of the array may change, which in turn can affect the performance of the app. Giving the object items unique keys can solve this issue in your case. ex)
{ label: 'Something', value: 4815, key: '...' },
Perhaps you can use "nanoid" instead, which can generate a unique key each time, as introduced in the "much better" part in this article Index as a key is an anti-pattern
I would like to add to my fellows over here. The short answer, it is not a good idea as already said. If the order of items in the array may change it can impact the performance negatively.
But why? I would like to provide a deeper dive explanation.
React uses a diffing algorithm, you can read more about it in their docs:
When diffing two trees, React first compares the two root elements. The behavior is different depending on the types of the root elements.
The diffing algorithm checks the old virtual DOM, which is a tree of elements to describe how the how the components should be rendered with tree. When the user interacts with the application and causes a state or props change, a new tree is being generated and a search between the two trees is being made to find difference between them.
If differences are found, the virtual DOM will be replaced with the parts that were changed.
Now, why am I explaining all of this? because in order for React to keep track on all of your generated <div> elements between those changes the key prop is being used, then, React can match those elements between the old tree and the new tree and know it does not need to generate them again if they were there before.
If you give your elements in the array the index as a key, which like already mentioned, can change, React might lose track of those elements and generate them again which is an unnecessary action that can be avoided. So, if you will give your elements a unique key that cannot change you are making React's life easier by helping it track those elements without them being lost along the way and those elements don't have to be generated over and over between tree changes.