Why Keys Matter
Why Keys Matter
Keys help React identify which items have changed, been added, or removed.
How React Uses Keys
When a list is rendered, React uses keys to:
- Identify which items are the same across renders
- Track item identity for efficient updates
- Preserve state of components that haven't changed
Without Keys
// Bad: No keys
function TodoList({ todos }) {
return (
<ul>
{todos.map((todo) => (
<li>{todo.text}</li> // Warning: Each child needs a key
))}
</ul>
);
}
With Keys
// Good: With keys
function TodoList({ todos }) {
return (
<ul>
{todos.map((todo) => (
<li key={todo.id}>{todo.text}</li>
))}
</ul>
);
}
Performance Impact
Without proper keys:
- React may re-render all items unnecessarily
- Component state may be lost or mixed up
- Animations and transitions may break
Choosing Keys
Choosing Keys
Best Options
- Unique IDs from data (preferred)
{users.map((user) => (
<UserCard key={user.id} user={user} />
))}
- Stable unique values
{users.map((user) => (
<UserCard key={user.email} user={user} />
))}
- Index as last resort
// Only if list is static and won't reorder
{items.map((item, index) => (
<li key={index}>{item.name}</li>
))}
When Index is OK
- List is static (no additions/removals)
- List won't be reordered
- Item has no state or lifecycle methods
- Item won't be filtered or sorted
Generating Keys
// From API data
{users.map((user) => (
<li key={user.id}>{user.name}</li>
))}
// Generated (less ideal)
{items.map((item, index) => (
<li key={`item-${index}`}>{item.name}</li>
))}
// From unique property
{products.map((product) => (
<li key={product.sku}>{product.name}</li>
))}
Key Anti-patterns
Key Anti-patterns
Don't Use Math.random()
// Bad: Random keys on every render
{items.map((item) => (
<li key={Math.random()}>{item.name}</li>
))}
Problems:
- New key every render = full re-render
- State is never preserved
- Performance is terrible
Don't Use Non-Unique Values
// Bad: Duplicate keys
{users.map((user) => (
<li key={user.name}>{user.name}</li>
))}
// What if two users have the same name?
Don't Use Complex Objects
// Bad: Object reference changes every render
{items.map((item) => (
<li key={{ id: item.id }}>{item.name}</li>
))}
Key Takeaways
// Good
{items.map((item) => (
<li key={item.id}>{item.name}</li>
))}
// Acceptable (if list is static)
{items.map((item, index) => (
<li key={index}>{item.name}</li>
))}
// Bad
{items.map((item) => (
<li key={Math.random()}>{item.name}</li>
))}
Practice Problems
Create a reusable React component implementing Keys. Include proper state management and accessibility.
Solution
// Production-ready component with:
// - Proper TypeScript types
// - Accessibility (ARIA)
// - Error boundaries
// - Loading states
// - Memoization where neededWrite unit and integration tests for Keys using React Testing Library.
Solution
// Test coverage:
// 1. Rendering tests
// 2. Interaction tests
// 3. Edge case tests
// 4. Accessibility testsOptimize Keys for performance. Consider memoization, code splitting, and bundle size.
Solution
// Optimization techniques:
// 1. React.memo / useMemo / useCallback
// 2. Code splitting with lazy()
// 3. Virtual scrolling for lists
// 4. Image lazy loading
// 5. Bundle analysisQuiz
1. Why do we need keys in React lists?
2. What is the best source for keys?
3. When is it OK to use array index as key?
4. Why should you avoid Math.random() as keys?
Flashcards
Question
Why are keys important?
Click to reveal answer
Answer
They help React identify changed items for efficient updates
Question
What is the best source for keys?
Click to reveal answer
Answer
Unique IDs from your data
Question
When is array index OK as key?
Click to reveal answer
Answer
When the list is static and won't reorder
Question
Why avoid Math.random() as keys?
Click to reveal answer
Answer
It creates new keys every render, causing unnecessary re-renders
Question
What is Keys?
Click to reveal answer
Answer
Keys is a key concept in frontend development.
Revision Notes
Key Takeaways
- 1.Keys help React identify changed items
- 2.Use unique IDs from your data
- 3.Avoid Math.random() as keys
- 4.Array index is OK for static lists
- 5.Good keys improve performance
Interview Tips
- •Explain why keys are needed
- •Show how to choose appropriate keys
- •Discuss key anti-patterns
Cheat Sheet
Cheat Sheet
Key Rules
- Unique among siblings
- Stable across renders
- Prefer unique IDs
- Avoid Math.random()
Good Keys
// From data
key={item.id}
key={item.email}
key={item.sku}
Bad Keys
// Random
key={Math.random()}
// Complex object
key={{ id: item.id }}
// Non-unique
key={item.name}
When Index is OK
- Static list
- No reorder
- No filtering/sorting
- No item state