DEV Community

Makoto Tsuga
Makoto Tsuga

Posted on

"Is it better not to put the map index into the 'key' prop?"

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>
));
Enter fullscreen mode Exit fullscreen mode

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>);
Enter fullscreen mode Exit fullscreen mode

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",
  },
];
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
sheraz4194 profile image
Sheraz Manzoor

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.