Documentation
Rules
no-array-index-key

no-array-index-key

Rule category

Suspicious.

What it does

Warns when an array index is used as a key prop.

Why is this bad?

The order of items in a list rendering can change over time if an item is inserted, deleted, or the array is reordered. Indexes as keys often lead to subtle and confusing errors.

Examples

Failing

import React from "react";
 
interface ExampleProps {
  items: { id: string; name: string }[];
}
 
function Example({ items }: ExampleProps) {
  return (
    <ul>
      {items.map((item, index) => (
        //              ^^^^^
        //              - Do not use Array index as key.
        <li key={index}>{item.name}</li>
      ))}
    </ul>
  );
}

Passing

import React from "react";
 
interface ExampleProps {
  items: { id: string; name: string }[];
}
 
function Example({ items }: ExampleProps) {
  return (
    <ul>
      {items.map((item) => (
        <li key={item.id}>{item.name}</li>
      ))}
    </ul>
  );
}

Further Reading