Sub topic 4
Why every item needs a stable key
This chapter assumes you can already render a basic list with for:each and for:item. It also assumes you know that a template binds class properties with curly braces. Here you will learn what the key attribute does, where it goes, and which values make a good key.
What the key does
When the array changes, LWC compares the old list with the new one and updates the page. The key tells LWC which new item corresponds to which old item. With that match, LWC can reuse an existing DOM element and move or remove only the elements that changed.
Without a reliable match, LWC pairs items by position. Elements then end up showing the wrong item's state.
Where the key goes
Put key on the first element directly inside the iteration template. The for:each directive and the iterator directive follow the same rule.
<template>
<ul>
<template for:each={contacts} for:item="contact">
<li key={contact.Id}>{contact.Name}</li>
</template>
</ul>
</template>The value must be a bound property, such as {contact.Id}. A literal string such as key="abc" gives every item the same key. Templates cannot run expressions, so you cannot build a key inline. If you need a computed key, add it to each object in JavaScript.
What makes a good key
A good key has three properties:
- Unique among the siblings in that one list. Keys in different lists can repeat.
- Stable, meaning the same item keeps the same key every time the list renders.
- A string or a number.
A record Id, a database primary key, or an Id you generate once when you create the object all work. Names often fail the uniqueness test.
Why the index is a bad key
The for:index value is the item's position. It is unique, but it is not stable. Remove the first item and every later item gets a new index.
The next example shows the effect. Each row has an editable text input, and a button removes the row.
<template>
<ul>
<template for:each={tasks} for:item="task" for:index="position">
<li key={position}>
<input type="text" value={task.label} />
<button data-id={task.id} onclick={handleRemove}>Remove</button>
</li>
</template>
</ul>
</template>import { LightningElement } from 'lwc';
export default class TaskList extends LightningElement {
tasks = [
{ id: 't1', label: 'Draft' },
{ id: 't2', label: 'Review' },
{ id: 't3', label: 'Publish' }
];
handleRemove(event) {
const id = event.currentTarget.dataset.id;
this.tasks = this.tasks.filter((task) => task.id !== id);
}
}Type extra text into the "Draft" input, then remove the "Draft" row. With key={position}, the first li keeps key 0 and is reused for "Review". The text you typed stays in that input, because the DOM element and its typed value were kept. The row now shows the wrong text.
Change the key to {task.id} and LWC removes the element for t1. The typed text goes with it, and the other rows are untouched.
Diagnosing key problems
| Symptom | Likely cause | Fix |
|---|---|---|
| Compile error about a missing key | `key` is absent, or sits on an element that is not the first one inside the iteration template | Add `key={...}` to the first element |
| Console error or warning about duplicate keys | Two items share a value, such as a non-unique name | Use a unique field such as `Id` |
| Inputs or styles stick to the wrong row after a change | The key is `for:index` or another unstable value | Use the item's own Id |
Summary
The key identifies an item across renders. Place it on the first element inside the iteration template, bind it to a unique and stable value, and never use the position.
Exercise
A list renders <li key={position}> using for:index="position". A user deletes the second item, and the third item's checkbox now appears unchecked while the old second item's state remains. Explain why this happens and give the fix.
Show answer
With an index key, the third item moves from key 2 to key 1. LWC matches by key, so it reuses the old second item's element for the third item's data. The element keeps its checked state, so the state looks like it belongs to the wrong item. The fix is to use a unique, stable field from the data, such as key={item.id}, so each element stays tied to its own item.