Can index be used as a key prop?

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:

  1. 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.

  2. 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 with key = 1 now gets key 2 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?

  1. When the list data won't be filtered, sorted or modified.
  2. When there's no other unique identifier available, and implementing one would be challenging.

Do you accept cookies?

Cookies are small amounts of data saved locally on you device, which helps our website - it saves your settings like theme or language. It helps in adjusting ads and in traffic analysis. By using this site, you consent cookies usage.