JavaScript, Web Development, and other stuff.

🏡 Home

Lists and the Key Prop in React

July 01, 2019 - 2 min read

If you’ve ever used React, you’ve likely seen this warning in your console at some point:
Warning: Each child in a list should have a unique "key" prop.

Why does each child in a list need to have a unique “key” prop?

The foremost reason is that using the “key” prop in a list can significantly boost your apps performance 🚀

Using a “key” prop, when rendering lists gives each item in the list a unique identifier. With an identifier, React is able to determine which items have been added, removed, or changed. When React goes through its reconciliation process, it can tell which items have been mutated and which have not, and will update the DOM accordingly.

Using a stable identifier as your “key”, like an id, ensures that even if the order of the items change, React will still be able to tell which list items have been mutated.

Good practice:

const animals = [
  { id: "animal_zebra", label: "Zebra" },
  { id: "animal_kangaroo", label: "Kangaroo" },
  { id: "animal_rabbit", label: "Rabbit" },
]

const AnimalList = () => (
  <div>
    {animals.map((animal) => (
      <div key={animal.id}>{animal.label}</div>
    ))}
  </div>
)

In the above example, if we were to remove ‘Zebra’ from the list, React would only mutate the item with the id of ‘zebra’, and leave the others untouched.

On the other hand, if we were to use the index as the “key” prop, and an item was removed from the beginning or middle of the list, all of the “keys” of items that come afterward would change, and React would assume that all of those items have been mutated too. React will then update every child when re-rendering, which is very inefficient.

Bad practice:

const animals = ["Zebra", "Kangaroo", "Rabbit"]

const AnimalList = () => (
  <div>
    {animals.map((animal, index) => (
      <div key={index}>{animal}</div>
    ))}
  </div>
)

In the above example, if we were to remove ‘Zebra’ from the list, all of the items in the list would receive a new “key” prop, and React would inefficiently re-render each item.

TLDR; Use unique/stable values for the “key” prop in React lists to improve performance.

THE END


Adam Feldman
Written by Adam Feldman who lives and works in Toronto, Canada.