Sub topic 4
Why Every Item Needs a Stable Key
This chapter assumes you can read an LWC template and a component class. It also assumes you know what for:each does and can bind a property with curly braces. Here you will learn what the key attribute does, how to choose a good one, and how to recognize the errors that bad keys cause.
What the key is for
When a list changes, the LWC engine does not throw away the old DOM and build it again. It compares the old list of rendered items with the new one and changes only what differs. To compare them, it must know which new item corresponds to which old item. The key attribute provides that link.
A key is an identity tag for one item. If an item has the same key before and after an update, the engine treats it as the same item. It keeps the existing DOM element, moves it if its position changed, and updates only the parts that differ. If a key appears for the first time, the engine creates an element. If a key disappears, the engine removes that element.
Without reliable keys, the engine cannot tell "this item moved" from "this item was replaced". It then reuses or recreates elements in ways you did not intend.
The rules for a key
The rules are short, and the compiler enforces some of them.
- Put
keyon the first element inside the iteration template. Withfor:each, that is the first child of<template for:each>. Withiterator, it is the first child of<template iterator:name>. - The value must be a string or a number.
- The value must be unique among the items in that one list. Two lists on the same page can reuse the same values.
- The value must be stable. The same logical item must get the same key every time the list renders.
- Do not use the
for:indexvalue as the key.
Here is the basic correct form, using the data from the earlier chapters.
<!-- contactList.html -->
<template>
<ul>
<template for:each={contacts} for:item="contact">
<li key={contact.Id}>{contact.Name}</li>
</template>
</ul>
</template>// contactList.js
import { LightningElement } from 'lwc';
export default class ContactList extends LightningElement {
contacts = [
{ Id: '003A', Name: 'Amy Taylor' },
{ Id: '003B', Name: 'Ravi Patel' },
{ Id: '003C', Name: 'Lena Fischer' }
];
}The <template> tag with for:each is not rendered. It only marks the loop. The <li> is the first real element, so it carries the key.
What goes wrong without a key
The compiler checks the template when you build the component. If you leave out key on the first element in the iteration, deployment or the local build fails with an error that says the element inside the iteration needs a key attribute. You find this problem early.
The harder problems come from a key that exists but is wrong. The compiler cannot check whether a value is unique or stable, because that depends on your data at run time. The three wrong choices below are the ones you will meet most.
Missing key
This is the easy case. The compiler rejects it, and you add the attribute. Check also that the key is on the first element and not on a deeper child. A key on a nested <span> inside the <li> does not satisfy the rule.
Duplicate keys
Suppose two items share a key. The engine cannot tell them apart, so it may reuse one element for both or update the wrong one. The result is rows that show the wrong data, or rows that disappear when you change a different row. In development mode, LWC may log a warning about duplicate keys, but you should not rely on that.
Duplicates usually come from one of these causes:
- A field that looks unique but is not, such as
Nameor an email shared across records. - Data merged from two sources that each have their own ids.
- A query that joins records so the same parent Id appears on several rows.
When the data has no natural unique field, build one when you prepare the list. For example, combine two fields into a string, or number the rows when you first load the data and keep that number with the row.
Index as key
Using the position as the key is the most common mistake, because it always looks unique and it always passes the compiler.
<!-- Avoid: the key changes meaning whenever the list changes -->
<template for:each={contacts} for:item="contact" for:index="position">
<li key={position}>{contact.Name}</li>
</template>The index is unique, but it is not stable. It identifies a slot, not an item. If you remove the first contact, the old second contact moves to index 0. The engine sees "key 0 still exists" and reuses the first element for a different person. For plain text this only costs extra work. For anything with its own state, it produces visible bugs.
The next section shows one such bug.
A concrete failure: state attached to the wrong row
Consider a list where each row has a text input. The user types a note into the first row, then you remove the first contact.
<!-- noteList.html -->
<template>
<button onclick={removeFirst}>Remove first</button>
<ul>
<template for:each={people} for:item="person" for:index="position">
<li key={position}>
{person.Name}
<input type="text" placeholder="Note" />
</li>
</template>
</ul>
</template>// noteList.js
import { LightningElement } from 'lwc';
export default class NoteList extends LightningElement {
people = [
{ Id: 'p1', Name: 'Amy Taylor' },
{ Id: 'p2', Name: 'Ravi Patel' },
{ Id: 'p3', Name: 'Lena Fischer' }
];
removeFirst() {
this.people = this.people.slice(1);
}
}Type "call Monday" into Amy's input and click the button. The list now shows Ravi and Lena, but "call Monday" is still in the first input, next to Ravi's name. The engine kept the element for key 0 and only changed its text. The typed value lives in the input element, not in your data, so it stayed.
Change the key to person.Id and run it again. Now the engine sees that key p1 is gone and removes that row, input included. The note disappears with Amy, which is the correct outcome.
Where a good key comes from
Rank your options in this order.
| Source | Stability | Notes |
|---|---|---|
| Salesforce record Id | Stable | Best choice for records from Apex, `@wire` adapters, or the UI API. |
| Another unique id from the data source | Stable | Fine if the source guarantees uniqueness and never reuses it. |
| An id you assign once when data enters the component | Stable while the component lives | Use for client-side rows that have no Id yet. |
| A combination of fields | Stable if fields do not change | Check that the combination is unique. |
| Array index | Not stable | Do not use. |
| A random value generated during render | Never stable | Changes every render, so every row is rebuilt. |
The last row deserves attention. A key built with a random number or timestamp inside a getter changes on every render. The engine then sees every item as new, destroys every element, and builds them again. Nothing is wrong visibly, but you lose focus, scroll position and input state in each row, and you pay the full rendering cost.
For rows that do not exist in Salesforce yet, assign the id once, when the row is created, and store it on the object.
import { LightningElement } from 'lwc';
export default class DraftRows extends LightningElement {
nextId = 1;
rows = [];
addRow() {
const id = `draft-${this.nextId}`;
this.nextId += 1;
this.rows = [...this.rows, { id, label: `Row ${id}` }];
}
}Each row keeps its id for its whole life, even if other rows are inserted or removed around it.
Keys with the iterator directive
The iterator directive has the same rule. The key goes on the first element inside the template, and it reads from the current item through it.value.
<template>
<ul>
<template iterator:it={contacts}>
<li key={it.value.Id}>{it.value.Name}</li>
</template>
</ul>
</template>Using it.index as the key is the same mistake as using for:index.
How the engine uses keys
The following diagram shows what happens when the first item is removed from a three-item list, once with stable keys and once with index keys.
Debugging key problems
Work through these checks when a list behaves oddly after an update.
- A build error mentions
key. The first element inside the iteration has nokeyattribute, or the key is on a nested element. - Rows show the wrong data after a change. Look for duplicate keys. Log the keys and compare their count with the number of distinct values.
- Typed text, focus or checkboxes jump to another row. Look for index keys, or for keys that are reused for different items.
- Inputs lose focus on every keystroke or update. Look for keys that change on every render, such as random values or keys built from a field the user is editing.
- The key is
undefined. The property name is wrong, for examplecontact.idinstead ofcontact.Id. JavaScript is case sensitive. All items then share one key.
A quick way to check uniqueness is to run this in a method while debugging.
hasUniqueKeys(items, keyName) {
const keys = items.map((item) => item[keyName]);
return new Set(keys).size === keys.length;
}A false result means at least two items share a key value, or the property is missing from some items.
Summary of the working model
- The key tells the engine which new item is the same as which old item.
- It goes on the first element inside the iteration template.
- It must be a unique string or number within its list.
- It must stay the same for the same item across renders.
- Use the record Id when you have one. Assign your own id once when you do not.
- Never use the index or a value generated at render time.
Exercise
A component renders <li key={position}> using for:index="position". A user types in an input in the third row, and then another part of the app inserts a new item at the start of the list. Where does the typed text appear afterward, and what change fixes it?
Show answer
The typed text stays in the element at index 2, which now shows the item that was previously second. The engine keeps the elements for keys 0, 1 and 2 and adds a new one for key 3, so state in the input is not tied to the item. Fix it by using a stable unique value, such as contact.Id, as the key, so the engine keeps the input with its original item and creates a new element for the inserted one.
Exercise
A developer sets key={contact.Name}. Give two different problems this can cause.
Show answer
First, two contacts can have the same name, so the keys are duplicated and the engine may reuse or update the wrong element. Second, if the name is editable, changing it changes the key, so the engine treats the row as a new item and rebuilds it, which loses focus and input state.
Exercise
Why can the compiler catch a missing key but not an index key or a duplicate key?
Show answer
A missing key is a fact about the template text, which the compiler can read at build time. Whether a key value is unique or stable depends on the data that exists at run time, which the compiler cannot see.