Course contentsShow
← React
Lesson 169 of 2,3965. Lists and KeysFree lesson

Refactoring from Index Keys: A Case Study

Step-by-step example of fixing an index-key bug by introducing proper unique identifiers to list data.

Refactoring from Index Keys: A Case Study

You'll learn: How to fix a real-world bug caused by index keys by adding proper unique identifiers to your data.

The Scenario

Imagine you've built a task list app where users can add, remove, and reorder tasks. You started with index keys (because it seemed harmless), but now users report weird bugs: deleted tasks reappear with wrong text, reordering scrambles their notes.

The Before: Broken Code

function TaskList() {
  const [tasks, setTasks] = useState([
    { text: "Buy groceries" },
    { text: "Walk dog" },
    { text: "Read book" }
  ]);

  return (
    <ul>
      {tasks.map((task, index) => (
        <li key={index}>{task.text}</li>
      ))}
    </ul>
  );
}

The problem: Your tasks array has no unique ID. React relies on the index, which changes when you reorder or delete items.

The Fix: Add Stable IDs

Step 1: Add unique IDs to your data structure when tasks are created:

const [tasks, setTasks] = useState([
  { id: 1, text: "Buy groceries" },
  { id: 2, text: "Walk dog" },
  { id: 3, text: "Read book" }
]);

Step 2: Use the ID as the key:

{tasks.map((task) => (
  <li key={task.id}>{task.text}</li>
))}

Step 3: When adding new tasks, generate IDs (simple counter or Date.now()):

const addTask = (text) => {
  setTasks([...tasks, { id: Date.now(), text }]);
};

Now deleting task #2 won't cause React to think task #3 became task #2. Each item maintains its identity.

Key Takeaway: Refactoring from index keys means modifying your data structure to include stable, unique identifiers and then using those IDs as keys instead of array positions.