What Is the key Prop?
The key prop is a special attribute that helps React identify elements uniquely in a list.
items.map(item => (
<li key={item.id}>{item.name}</li>
))
Keys are not passed as props to components — they are used internally by React.
🧠 Why React Needs key
React uses reconciliation to update the DOM efficiently.
When a list changes (add, remove, reorder):
- React compares old Virtual DOM with new Virtual DOM
- Keys help React match elements correctly
Without keys, React must rely on element order, which causes problems.
🔥 Example Without Keys (Problem)
{["A", "B", "C"].map(item => (
<li>{item}</li>
))}
If "A" is removed:
["B", "C"]
React thinks:
- A → B
- B → C
→ Wrong mapping → DOM reuse bugs ❌
✅ Example With Keys (Correct)
{items.map(item => (
<li key={item.id}>{item.name}</li>
))}
Now React knows exactly:
- Which item changed
- Which DOM nodes to reuse
- Which ones to remove or insert
⚠️ Why Using Index as Key Is Dangerous
items.map((item, index) => (
<li key={index}>{item}</li>
))
❌ Problems:
- Reordering breaks mapping
- Inputs lose focus
- Wrong data displayed
- Unexpected UI bugs
✔ Index keys are safe only if:
- List is static
- Items never reorder, add, or remove
🧪 Real Bug Example
<input value={item.text} />
Using index as key:
- React reuses wrong input DOM
- User input jumps between items
🧠 How React Uses Keys Internally
React:
- Builds a map of old children using keys
- Matches new children using those keys
- Applies minimum DOM operations
- Preserves component state correctly
🎯 Short Interview Answer
The
keyprop helps React uniquely identify list items during reconciliation.
It allows React to efficiently update, insert, or remove elements without re-rendering the entire list and prevents UI bugs caused by incorrect DOM reuse.
⭐ One-Line Summary
Keys tell React which item is which so it can update lists efficiently and correctly.
✅ Best Practices
✔ Use stable, unique IDs
✔ Avoid array index as key
✔ Keys must be unique among siblings