Sobes.tech
Middle

What happens if you use an index as a key when rendering a list in React?

sobes.tech AI

Answer from AI

Using array index as a key when rendering lists in React can lead to performance issues and incorrect UI updates. The key helps React efficiently determine which elements have changed, been added, or removed.

If you use the index as a key, React may incorrectly match components when the order of elements changes or when inserting/deleting elements, which can cause:

  • Incorrect preservation of component state
  • Unnecessary re-renders
  • Errors in animations and focus

Indexes are only acceptable as keys if the list is static and does not change during the component's lifetime. In other cases, it is better to use unique and stable identifiers for elements.

Example of incorrect usage:

{items.map((item, index) => (
  <ListItem key={index} data={item} />
))}

Better:

{items.map(item => (
  <ListItem key={item.id} data={item} />
))}