Hello everyone. On DEV, I'd like to write down the feedback received from a senior developer during a code review of React.
One day, I put the index of map into key prop ...
In my portfolio, When creating the some elements by using map, I put map index into key prop. It is something like that.
const todoItems = todos.map((todo, index) => (
<li key={index}>{todo.text}</li>
));
We should avoid to use index of map.
My mentor asked me to avoid use the index of map. And I put the keys of todos instead of it.
const todoItems = todos.map((todo) =>
<li key={todo.id}>{todo.text}</li>);
Why index of map is not recommended to use?
Using the index as the key is not recommended for the following reason:
- As the list elements increase, each re-render generates a new index, making it uncertain to ensure a unique id for each item. As a result, it might have a negative impact on performance and cause issues with the state of components.
Hence, when you create some elements by using map, create id and use the keys in the array as much as possible.
const todo= [
{
id: 1,
text: "A",
},
{
id: 2,
text: "B",
},
{
id: 3,
text: "C",
},
{
id: 4,
text: "D",
},
];
Top comments (1)
I liked it, but unfortunately it is not possible every time!!
What if we are fetching data from an API, which does not contain id? In that case using index for key is the absolute best method.