Beginner LevelReact JS & React 19
Why are keys necessary when rendering lists in React and why avoid using array index as key?
❓ Interview Prompt: Explain React keys, Virtual DOM reconciliation algorithm, identity tracking across renders, and array index key bugs.
Keys help React identify which items in a list have changed, been added, or been removed during Virtual DOM reconciliation:
Why 'key={index}' Causes Bugs:
If items in a list are re-ordered, filtered, or prepended, using the array index as a key tricks React into thinking the component at index '0' is still the same element. This causes severe bugs with form inputs, stateful child components, and animation glitches!
Best Practice:
Always use stable, unique string/number IDs from your data model (e.g., 'item.id').
Code Implementation Example
jsx
// ❌ BAD: Using array index as key causes state corruption on list reorders
{items.map((item, index) => (
<TodoItem key={index} todo={item} />
))}
// ✅ GOOD: Using stable unique database ID as key
{items.map((item) => (
<TodoItem key={item.id} todo={item} />
))}💡Using stable item IDs as keys vs array index key anti-pattern.
🎯 Interview Key Takeaway
Keys must be stable, unique IDs. Avoid array indices as keys to prevent state corruption when lists reorder.
#Keys#Reconciliation#Lists#Virtual DOM#Beginner
Back to all React JS & React 19 Questions→