React's algorithm maintains a lightweight virtual DOM. When changes occur, it updates the virtual DOM and compares it with the real DOM. If it detects differences, it updates the DOM.
The key
attribute serves React in identifying list elements and tracking their changes. When rendering a list of elements, React defaults to using the index as the key but warns to provide a custom value.
The key should always be unique within the context of a specific list of elements. An index is not unique because when the list is modified, elements can change their positions.
Using the index as a key prop can introduce certain risks:
-
Performance: Consider a list with 4 elements. If an element is added at the beginning or in the middle of the list, the
key
of all subsequent elements will be changed, even if the components themselves haven't changed. React detects the key change and unnecessarily re-renders those components. However, assuming each key is unique, React knows it doesn't need to re-render unchanged elements. -
Incorrect rendering: React can confuse component states. Adding a new element at the beginning of the list might cause it to inherit the state of a component previously rendered with the same
key
. The previous component withkey = 1
now gets key2
and might be rendered as if it had the state of the component that previously had that key. This problem is described more comprehensively here.
When can an index be used as a key
?
- When the list data won't be filtered, sorted or modified.
- When there's no other unique identifier available, and implementing one would be challenging.