Reputation: 57
I am aware that I should not use the index as a key when mapping an array in react. Consensus seems to be to use something particular to that index as a key. My question is what do you normally use? Is it better to do something like this or is it no different to just using the index when you are mapping?
const usersWithId = users.results.map((user, index) => {
return (
{...user, id: index}
)
})
{usersWithId.map((user) => {
return (
<p key={user.id}>{user.id}</p>
)
})}
vs just using it with the index
{users.map((user, index) => {
return (
<p key={index}>{user.id}</p>
)
})}
Upvotes: 1
Views: 1022
Reputation: 775
The keys helps to react to identify wich elements have changed, have been added o removed and give to the element a "identity". The best way to pick a key is use a unique value that uniquely identifies one element among the others in the array, and is most often to use IDs from the data.
Use the index as key is the last resource you have to use and you have to be sure that the order of items in the array will not change.
This article is really good: https://robinpokorny.medium.com/index-as-a-key-is-an-anti-pattern-e0349aece318
Upvotes: 2