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

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

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.

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more