Can I use the index of an element (passed to a method/looped over) as the key attribute's value?

Question

Can I use the index of an element (passed to a method/looped over) as the key attribute’s value?

Answer

We can use the index of an element as the key attribute’s value, however, using only the index of an element as the key may cause some issues as the order of the elements may change and potentially render incorrect data specifically when a list can be reordered or filtered. When a list of elements can be reordered or filtered we should use more unique keys for the elements.

10 Likes

Like we have a standard attribute “id” for every element in html, is “key” a standard attribute given by JSX for the element?

reactJS complicated transpiling from react to vannila JS, the keys help reactJS for speed optimization behind the scenes.

1 Like

this is a good explanation on reactjs.org, about the #keys

When you don’t have stable IDs for rendered items, you may use the item index as a key as a last resort:

const todoItems = todos.map((todo, index) =>
  // Only do this if items have no stable IDs
  <li key={index}>
    {todo.text}
  </li>
);

We don’t recommend using indexes for keys if the order of items may change. This can negatively impact performance and may cause issues with component state. Check out Robin Pokorny’s article for an in-depth explanation on the negative impacts of using an index as a key. If you choose not to assign an explicit key to list items then React will default to using indexes as keys.

Here is an in-depth explanation about why keys are necessary if you’re interested in learning more.