Why Using Index as Key in React Lists Can Be Risky
In React, keys
help identify which items in a list have changed, been added, or been removed. A good key gives React a hint about which elements can be reused efficiently. Using the array index as a key might seem easy, but it can cause subtle bugs and performance issues in certain situations.
Here's why using index as a key is risky:
-
Incorrect Component Reordering:
If the list items can change their order, React will associate the wrong component state with the wrong item because it relies on the index position, not the content. -
Problems with State:
Suppose a list item holds some local state (like an input field). If the list changes and indexes shift, React might mistakenly preserve or overwrite the wrong state. -
Performance Issues:
React optimizes rendering by comparing the old and new virtual DOMs. If indexes are used as keys, React may re-render more components than necessary because it thinks items have changed when they haven't. -
Bad User Experience:
In interactive UIs (e.g., dynamic forms, drag-and-drop lists), using index as a key can lead to unexpected behaviors — like form inputs losing focus or wrong inputs being updated.
When is it (sort of) safe to use an index as a key?
- If the list is static and will never change order or items (e.g., a fixed menu).
- If the list items have no dynamic content, no local state, and no user interaction tied to them.
Best Practice:
Always use a unique and stable identifier from your data as the key — such as a database ID or a unique slug.
Example:
// Risky (Using Index) {items.map((item, index) => ( <div key={index}>{item.name}</div> ))} // Better (Using Unique ID) {items.map((item) => ( <div key={item.id}>{item.name}</div> ))}