gotchajavascriptreactMajorpending
Gotcha: React keys and list rendering pitfalls
Viewed 0 times
react keylist renderingindex keyunique keyreorder bug
Error Messages
Problem
Using array index as React key causes bugs: state leaks between items, incorrect animations, and stale data after reordering.
Solution
Key rules and common mistakes:
// BAD: Index as key (breaks on reorder/insert/delete)
{items.map((item, index) => (
<TodoItem key={index} item={item} />
))}
// If items reorder, React reuses components by index
// -> state (input values, checkboxes) stays at old position!
// GOOD: Stable unique ID as key
{items.map(item => (
<TodoItem key={item.id} item={item} />
))}
// BAD: Random key (remounts on every render)
{items.map(item => (
<TodoItem key={Math.random()} item={item} />
// Forces remount every render - destroys state, kills perf
))}
// BAD: Non-unique key
{items.map(item => (
<TodoItem key={item.name} item={item} />
// Two items with same name? Silent bugs
))}
// When index IS acceptable:
// 1. List is static (never reordered/filtered)
// 2. Items have no state (pure display)
// 3. Items have no stable ID
{staticLabels.map((label, i) => (
<span key={i}>{label}</span> // OK: static, no state
))}
// Generate IDs if you don't have them:
const [items, setItems] = useState([]);
const addItem = (text) => {
setItems(prev => [...prev, { id: crypto.randomUUID(), text }]);
};Why
React uses keys to match elements between renders. Wrong keys cause React to reuse the wrong DOM elements, leading to state leaking between unrelated items.
Context
React components rendering dynamic lists
Revisions (0)
No revisions yet.