JS Guide
HomeQuestionsSearchResources
Search

Built for developers preparing for JavaScript, React & TypeScript interviews.

ResourcesQuestionsSupport
HomeQuestionsSearchProgress
HomeQuestionsreact
PrevNext
react
junior
lists

Why are keys important when rendering lists in React?

keys
lists
rendering
performance
reconciliation
Quick Answer

Keys help React identify which items in a list have changed, been added, or removed. They should be unique among siblings and stable across renders. Using proper keys improves performance and prevents bugs with component state.

Detailed Explanation

Why Keys Matter:

  • React uses keys to track items during reconciliation
  • Without keys, React re-renders all items on any change
  • Proper keys enable efficient updates (only changed items)
  • Keys preserve component state and DOM identity

Key Rules:

  1. Keys must be unique among siblings
  2. Keys should be stable (same item = same key)
  3. Don't use array index as key (if list can reorder)
  4. Keys don't need to be globally unique

What to Use as Keys:

  • ✅ Database IDs
  • ✅ Unique identifiers from data
  • ✅ Generated UUIDs (if created once)
  • ⚠️ Index (only for static lists)
  • ❌ Random values (changes every render)

Code Examples

Correct key usage
function TodoList({ todos }) {
  return (
    <ul>
      {todos.map(todo => (
        // Use unique, stable identifier
        <li key={todo.id}>
          {todo.text}
        </li>
      ))}
    </ul>
  );
}

// Data with unique IDs
const todos = [
  { id: 1, text: 'Learn React' },
  { id: 2, text: 'Build an app' },
  { id: 3, text: 'Deploy' }
];

Resources

React Docs - Rendering Lists

docs

React Docs - Preserving and Resetting State

docs

Related Questions

How does React's reconciliation algorithm work?

senior
internals
Previous
What is state in React and how is it different from props?
Next
Why would you choose React over other frameworks like Vue or Angular?