React: using index as key for items in the list

this question has been asked before,

but the main answer could be found in the Docs of React

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.

there are no unexpected list update while adding or removing elements

but the main reason for this is the algorithm for indexing and comparing behind,

you can read about this here under ‘different-types’

The key here is to understand not everything in the DOM has a representation in React “Virtual DOM” and, because direct manipulations of the DOM (like a user changing an value or a jQuery plugin listening to an element) are unnoticed by React, not using unique and constant keys will end up with React recreating the DOM node of a component when the key is not constant (and losing any untracked state in the node) or reusing a DOM node to render another component when the key is not unique (and tying its state to this other component).

Here you have a live demo showing how awful the results are

Just add an item, change it, add more items and see what happens.

have a read here too

Leave a Comment