← Back to Chapters

React Keys & Re-renders

? React Keys & Re-renders

? Quick Overview

In React, the key prop uniquely identifies elements in a list. It helps React efficiently update, insert, or remove items during re-renders. Correct key usage improves performance and prevents unexpected UI behavior.

? Key Concepts

  • Keys help React track list items across renders
  • Stable keys preserve component state
  • Changing a key forces React to recreate a component
  • Incorrect keys can cause UI bugs and flickering

? Syntax & Theory

When rendering lists, React compares old and new virtual DOM trees. Keys allow React to match elements correctly and reuse DOM nodes when possible. Without keys, React may unnecessarily re-render items.

? View Code Example
// Rendering a list without keys (inefficient)
function TodoList({ todos }) {
return (
<ul>
{todos.map(todo => (
<li>{todo.text}</li>
))}
</ul>
);
}
? View Code Example
// Rendering a list with stable keys (recommended)
function TodoList({ todos }) {
return (
<ul>
{todos.map(todo => (
<li key={todo.id}>{todo.text}</li>
))}
</ul>
);
}

⚙️ How Keys Affect Re-renders

  • If the key changes, React unmounts and remounts the element
  • If the key stays the same, React updates only changed props
  • Keys help preserve local state like input values
? View Code Example
// Changing the key forces input reset
function InputBox({ id }) {
return <input key={id} placeholder="Type here..." />;
}

? Explanation

When the id value changes, React treats the input as a new element. The previous input is unmounted and its state is discarded.

? Choosing Good Keys

  • Always use unique and stable identifiers
  • Avoid using array indexes as keys
  • Indexes break when items are reordered or deleted
  • Keys must remain consistent for the same item
? View Code Example
// Bad vs good key usage
{todos.map((todo, index) => (
<li key={index}>{todo.text}</li>
))}

{todos.map(todo => (
<li key={todo.id}>{todo.text}</li>
))}

? Tips & Best Practices

  • Prefer database IDs or UUIDs for keys
  • Keys are not accessible as props inside components
  • Use keys to intentionally reset component state
  • Never reuse the same key for different items

? Try It Yourself

  1. Create a todo list using unique IDs as keys
  2. Reorder items and observe stable rendering
  3. Replace IDs with index keys and notice bugs
  4. Add inputs inside list items and test state preservation

Goal: Understand how correct key usage improves rendering efficiency and prevents unnecessary re-renders.