Skip to content
beginnerPhase 36 · React

Keys

Use keys correctly for list rendering and understand reconciliation.

30m
0 problems
Topic Progress0%

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:

  1. Identify which items are the same across renders
  2. Track item identity for efficient updates
  3. 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

  1. Unique IDs from data (preferred)
{users.map((user) => (
  <UserCard key={user.id} user={user} />
))}
  1. Stable unique values
{users.map((user) => (
  <UserCard key={user.email} user={user} />
))}
  1. 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

0/3solved
Build Keys Component

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 needed
Keys Testing

Write 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 tests
Keys Performance

Optimize 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 analysis

Quiz

1. Why do we need keys in React lists?

Question 1 options

2. What is the best source for keys?

Question 2 options

3. When is it OK to use array index as key?

Question 3 options

4. Why should you avoid Math.random() as keys?

Question 4 options

Flashcards

Question

Why are keys important?

Answer

They help React identify changed items for efficient updates

Question

What is the best source for keys?

Answer

Unique IDs from your data

Question

When is array index OK as key?

Answer

When the list is static and won't reorder

Question

Why avoid Math.random() as keys?

Answer

It creates new keys every render, causing unnecessary re-renders

Question

What is Keys?

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