JS Guide
HomeQuestionsTopicsCompaniesResources
BookmarksSearch

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

ResourcesQuestionsSupport
HomeQuestionsSearchProgress
HomeQuestionsreact
PrevNext

Learn the concept

Lists & Keys

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 usageJSX
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' }
];

Real-World Applications

Use Cases

Infinite Scroll Feeds

Rendering large lists of social media posts with proper keys for efficient updates

Data Table Rendering

Displaying and sorting tabular data where keys ensure correct row identity during reordering

Drag-and-Drop Reordering

Keys maintaining component state during list item reordering operations

Mini Projects

Key Bug Demonstrator

beginner

Build a list app that shows the visual difference between index keys and unique keys when reordering

Virtualized List

intermediate

Implement a windowed list renderer that only renders visible items using proper keys

Industry Examples

Twitter/X

Feed rendering with unique tweet IDs as keys for efficient timeline updates

TanStack Virtual

Virtualized list library that relies on stable keys for performance

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?
PrevNext