Index as a key is an anti-pattern

Robin Pokorny
4 min readOct 12, 2015

So many times I have seen developers use the index of an item as its key when they render a list.

todos.map((todo, index) => (
<Todo {...todo} key={index} />
));
}

It looks elegant and it does get rid of the warning (which was the ‘real’ issue, right?). What is the danger here?

It may break your application and display wrong data!

Let me explain, a key is the only thing React uses to identify DOM elements. What happens if you push an item to the list or remove something in the middle? If the key is same as before React assumes that the DOM element represents the same component as before. But that is no longer true.

Stephen describes the problem he run into on egghead.io

To demonstrate the potential danger I created a simple example (with source).

Screenshot of the example showing the danger of using the index as key.

It turns out, when nothing is passed React uses the index as key because it is the best guess at the moment. Moreover, it will warn you that it is suboptimal (it says that in a bit confusing words, yes). If you provide it by yourself React just thinks that you know what you are doing which — remember the example — can lead to unpredictable results.

Better

--

--

Robin Pokorny

Zealous Engineer — TypeScript & Tech Leadership — Speaks — Loves maths — Reads specs — Vzhurudolu.cz podcast — Lives in Berlin