Keys & Reconciliation — React

Whenever the data changes, React runs the component again (a re-render) and gets a new description of the UI, made of JavaScript objects and called the…

The previous lesson left one question open: why can key={index} make React match the wrong items? The answer is in how React updates the page.

Every time the data changes, React runs your component again (a re-render), then compares the new result with the old one. From that comparison React learns which parts of the page need changing. This comparing is called reconciliation. In a list, React matches old items with new items by their key.

It's like a teacher who keeps notes on students by seat number: "seat 1 likes football". Once a new student sits in seat 1 and every other student moves to the next seat, that note now belongs to the new student. If the notes are kept by student ID number instead, a note always follows its student. key={index} is the seat number, and key={s.id} is the student ID.

Rendering again, and reconciliation

The rules React uses when it compares:

  1. A different element type, say a <div> that becomes a <span>: the old element is thrown away with everything inside it, and React makes a new one.
  2. The same element type: the element is reused, and only the attributes and text that changed are updated.
  3. In a list, old and new items are matched by key. An element with the same key is reused. A new key gets a new element. The element of a key that's gone is thrown away.

A reused element keeps everything inside it: text already typed into an <input>, the cursor position, focus. That is why key matters: the key decides which old element is used for which item.

The key={index} bug: the note changes rows

The StudentList component below shows each student's name and a note box, with index as the key:

function StudentList({ students }) {
  return (
    <ul>
      {students.map((s, index) => (
        <li key={index}>
          {s.name} <input placeholder="note" />
        </li>
      ))}
    </ul>
  );
}

What's in this <input> isn't managed by React: the text you type is kept by the <input> element itself, in the DOM. Say you type "likes football" in Andi's row, then Dewi is added at the very top. The students array changes from Andi, Budi, Citra to Dewi, Andi, Budi, Citra. Before you look at the table below, take a guess: whose row is "likes football" in now?

key Before After <input> used
0 Andi, holding "likes football" Dewi old input of key 0: "likes football"
1 Budi Andi old input of key 1: empty
2 Citra Budi old input of key 2: empty
3 not there yet Citra new input: empty

React sees that key 0 is still there, so the <li> and <input> of key 0 are reused. The name text is updated to Dewi, but what's in the input box isn't touched. So "likes football" appears in Dewi's row. Andi moves to key 1, whose box is empty, so Andi's note is gone. No error and no warning: the page is wrong without any sign.

The same happens when the list is sorted, filtered, or an item is removed from the middle: the items' positions shift, and what was typed moves to another student.

Use a stable id

Just change key={index} to key={s.id}:

<li key={s.id}>
  {s.name} <input placeholder="note" />
</li>

Each student's data now has an id: { id: 1, name: "Andi" }, { id: 2, name: "Budi" }, { id: 3, name: "Citra" }, then Dewi with id: 4.

key Before After <input> used
4 not there yet Dewi new input: empty
1 Andi, holding "likes football" Andi old input of key 1: "likes football"
2 Budi Budi old input of key 2
3 Citra Citra old input of key 3

Key 4 has never existed, so only Dewi gets a new element, which is inserted at the top. Andi, Budi and Citra are recognised by their id, so their elements stay. "likes football" stays in Andi's row. Only 1 new element is made, and nothing ends up in the wrong place.

Rules for picking a key

💡 Change the key to start from scratch

key can also go on a component outside a list. When a component's key changes, React treats it as a different component: the old one is thrown away, and a new one is made from scratch, with everything inside it.

In this code, selectedStudent holds the student who is selected, and that student's id is the key of NoteForm:

<NoteForm key={selectedStudent.id} student={selectedStudent} />

When the selection changes from Andi to Budi, the key changes from 1 to 2. So the form is made again, and its boxes are empty. Without the key, the old form is reused, and the note meant for Andi is still written there when Budi is picked.

⚠️ Keys that make typed text move or vanish

TL;DR: Whenever the data changes, React runs the component again (a re-render) and gets a new description of the UI, made of JavaScript objects and called the Virtual DOM. React compares that new description with the old one. This is called reconciliation, or diffing, and only the parts that differ are changed in the DOM. In a list, old and new items are matched by key (a name tag for each item): the same key means the old element is reused, along with what's inside it. key={index} (the item's position number) makes typed input text jump to another row once an item is inserted at the top, removed, or the list is sorted. Use key={item.id}: unique in that list and stable. Never Math.random(), because the key is new on every render. When a component's key changes, React throws the component away and makes a new one from scratch.

⚡ Render again, then compare

Meaning: Whenever the data changes, React runs the component again (a re-render) and gets a new description of the UI: JavaScript objects called the Virtual DOM. React compares that description with the old one, and this is called reconciliation. Then React changes only the parts of the DOM that differ. An element that stays the same is reused, along with what's inside it, such as text already typed into an <input>. In a list, old and new items are matched by key.

⚡ key={index} moves the note to another row

Write:

<li key={index}>
  {s.name} <input placeholder="note" />
</li>
Guess first: this row is made by students.map((s, index) => ...), so index is each student's position number. You type "likes football" in Andi's row, the first one, then Dewi is added at the very top. Whose row is "likes football" in now?

Dewi's. Dewi is now at position 0, so Dewi gets key 0. Key 0 already existed, so the <input> of key 0 is reused. The name text changes to Dewi, but what's in the box isn't touched.

Meaning: No error and no warning: the page is wrong without any sign. The same happens when the list is sorted, filtered, or an item is removed.

⚡ Use a stable id

Write:

<li key={s.id}>
  {s.name} <input placeholder="note" />
</li>

Meaning: s.id is the id from each student's data, and it doesn't change when the order does. Every student is recognised by their id, so their elements stay and "likes football" stays in Andi's row. Never Math.random() (a random number): the key is new on every render, so every element is remade.

⚡ Change the key to start from scratch

Write:

<NoteForm key={selectedStudent.id} student={selectedStudent} />

Meaning: NoteForm is a note form component, and selectedStudent holds the student who is selected. When a component's key changes, React treats it as a different component: the old one is thrown away, and a new one is made from scratch. So when the selection changes from Andi to Budi, the key changes too, and the form's boxes are empty again.

What you will learn