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
- Rendering means React runs your component function to find out what should show. The result isn't a page yet, but a description made of JavaScript objects: "there's a
<ul>, holding three<li>". This description is often called the Virtual DOM. - When the data changes (later you'll use state, data that can change, for this), React runs the component again and gets a new description.
- Reconciliation, often also called diffing: React compares the new description with the old one, then changes the real DOM (the elements actually on the page) only where they differ. An element that stays the same is reused, not made again.
The rules React uses when it compares:
- 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. - The same element type: the element is reused, and only the attributes and text that changed are updated.
- 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
- Unique among the items of one list. It doesn't have to be unique across the whole app.
- Stable: the same for the same item on every render. An
idfrom the database is the safest. - Never
Math.random():Math.random()gives a new random number every time it's called, so the key is new on every render. As a result, React throws away and remakes every element. Everything typed is lost, and it's more work. indexis fine only for a list that never gets items added at the top or in the middle, never has items removed, and is never sorted.- Data made in the browser with no id yet? Make an id when the item is created, for example with
crypto.randomUUID()(a function built into the browser that makes a unique id), and keep it with the data. Don't make it insidemap, becausemapruns on every render, so the id would be new every time.
💡 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
key={index}in a list that can change. Input text, focus and anything else an element keeps moves to the wrong item, with no error.key={Math.random()}. Every element is remade on every render: typed text is lost, and it's slower.- Two items with the same key. React warns
Encountered two children with the same key, and items can vanish or appear twice. - The key on the wrong element. The key goes on the outermost element
mapreturns, for example<li key={s.id}>, not on the<input>inside it. A component also can't read its own key as a prop: if it needs the id, pass it in another prop, such asid={s.id}.
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.