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

Each such item should have a permanent and unique property. Ideally, it should be assigned when the item is created. Of course, I am speaking about an id. Then we can use it the following way:

{todos.map((todo) =>

<Todo {...todo}

key={todo.id} />

)}

Note: First look at the existing properties of the items. It is possible they already have something that can be used as an id.

One way to do so it to just move the numbering one step up in the abstraction. Using a global index makes sure any two items would have different ids.

todoCounter = 1; function createNewTodo(text) {

return {

completed: false,

id: todoCounter++,

text

}

}

Much better

A production solution should use a more robust approach that would handle distributed creation of items. For such, I recommend shortid. It quickly generates ‘short non-sequential url-friendly unique’ ids. The code could look like the following: