Sub topic 11
Updating a list so the template re-renders
This chapter assumes you can already render an array with for:each, give each item a key, and bind properties in a template. It covers how to change the array so the DOM follows. You will see which assignments trigger a render, which mutations don't, and how keys decide what the engine does with existing elements.
How LWC decides to re-render
A component re-renders when a field it uses in the template changes. Since Spring '20, every class field is reactive. For objects and arrays, though, "changes" means the field is assigned a new value. LWC does not watch what happens inside a plain array or object.
| Operation on `this.contacts` | Triggers re-render? |
|---|---|
| `this.contacts = [...this.contacts, item]` | Yes, the field has a new array |
| `this.contacts = this.contacts.filter(...)` | Yes, `filter` returns a new array |
| `this.contacts.push(item)` | No, the field still holds the same array |
| `this.contacts[0].Name = 'X'` | No, the field still holds the same array |
| `this.contacts.sort(...)` | No, it sorts in place |
The rule for plain fields is to build a new array and assign it. The array methods map, filter, slice, concat and the spread operator already return new arrays. The mutating methods push, splice, sort, reverse and pop do not.
Add, remove, update and reorder
Each common change maps to one array operation that returns a new array. The component below uses all four.
// contactList.js
import { LightningElement } from 'lwc';
export default class ContactList extends LightningElement {
nextNumber = 4;
contacts = [
{ Id: '003A', Name: 'Amy Taylor' },
{ Id: '003B', Name: 'Ravi Patel' },
{ Id: '003C', Name: 'Lena Fischer' }
];
get hasContacts() {
return this.contacts.length > 0;
}
addContact() {
const id = `new-${this.nextNumber}`;
this.nextNumber += 1;
this.contacts = [
...this.contacts,
{ Id: id, Name: `New Contact ${this.nextNumber - 1}` }
];
}
removeContact(event) {
const id = event.currentTarget.dataset.id;
this.contacts = this.contacts.filter((contact) => contact.Id !== id);
}
renameContact(event) {
const id = event.currentTarget.dataset.id;
this.contacts = this.contacts.map((contact) =>
contact.Id === id
? { ...contact, Name: `${contact.Name} (edited)` }
: contact
);
}
sortByName() {
this.contacts = [...this.contacts].sort((a, b) =>
a.Name.localeCompare(b.Name)
);
}
}<!-- contactList.html -->
<template>
<lightning-button label="Add" onclick={addContact}></lightning-button>
<lightning-button label="Sort by name" onclick={sortByName}></lightning-button>
<ul lwc:if={hasContacts}>
<template for:each={contacts} for:item="contact">
<li key={contact.Id}>
{contact.Name}
<button data-id={contact.Id} onclick={renameContact}>Rename</button>
<button data-id={contact.Id} onclick={removeContact}>Remove</button>
</li>
</template>
</ul>
<p lwc:else>No contacts to show.</p>
</template>Four details in this code matter:
- Add. The spread operator copies the existing items into a new array and appends the new one. The new item gets an
Idthat cannot collide with an existing one. - Remove.
filterkeeps every item whoseIddiffers from the clicked one. TheIdcomes fromdata-id, as in the previous chapter on list item events. - Update.
mapreturns the same object for untouched items and a new object, built with{ ...contact }, for the changed one. Untouched items keep their identity. Only the edited one is new. - Sort.
sortmutates, so the code copies first with[...this.contacts], then sorts the copy and assigns it.
When the last contact is removed, hasContacts becomes false and the lwc:else paragraph appears. The empty-list fallback needs no extra code in the handlers.
What happens to the DOM
After the new array is assigned, the engine runs the template again and compares the old and new lists by key. It does not rebuild the whole list.
- A key present only in the new list creates a new
<li>. - A key present only in the old list removes that
<li>. - A key present in both reuses the existing
<li>. If the order changed, the element is moved. If the item's data changed, only the changed text or attributes are patched.
This is why the key must be a stable identifier from the data, such as a record Id. After sortByName, the element for Amy is still Amy's element, just in a new position. Anything attached to that element survives the move. That includes focus, text typed into an input, and the state of a child component.
A key based on position breaks this. Suppose the key is for:index. After a sort or a removal, key 0 now points to a different contact. The engine reuses the first element and rewrites its text. A child component in that element keeps its state from the old contact. You see the wrong input value or the wrong expanded row, and no error is raised.
Several changes, one render
LWC batches renders. If a handler assigns to several fields, or assigns to the same field twice, the template runs once after the handler finishes.
handleReset() {
this.contacts = [];
this.selectedId = undefined;
this.contacts = [{ Id: '003A', Name: 'Amy Taylor' }];
}The user sees only the final state: one contact and no selection. You can build a list in a loop with several assignments without extra renders, although building it locally and assigning once is clearer.
Items you cannot mutate
Some arrays arrive read-only. Two common sources:
@apiproperties. A value passed from a parent is read-only inside the child. Callingthis.items.push(x)or settingthis.items[0].Namethrows an error. Copy the data into a private field, or build a new array from it.- Wire results. Data returned by
@wireis read-only. Treatdataas input, not as a place to edit.
import { LightningElement, api } from 'lwc';
export default class ContactPicker extends LightningElement {
_contacts = [];
selectedIds = [];
@api
get contacts() {
return this._contacts;
}
set contacts(value) {
// Copy each record so local edits never touch the parent's data.
this._contacts = (value || []).map((contact) => ({ ...contact }));
}
toggle(event) {
const id = event.currentTarget.dataset.id;
this.selectedIds = this.selectedIds.includes(id)
? this.selectedIds.filter((existing) => existing !== id)
: [...this.selectedIds, id];
}
}The setter makes a shallow copy of each record. Selection state lives in a separate array of Ids, so toggling a row never changes the records.
The `@track` alternative
The @track decorator makes a field's contents deeply observed. With it, this.contacts.push(item) and this.contacts[0].Name = 'X' do trigger a render.
import { LightningElement, track } from 'lwc';
export default class TrackedList extends LightningElement {
@track contacts = [{ Id: '003A', Name: 'Amy Taylor' }];
addContact() {
this.contacts.push({ Id: '003B', Name: 'Ravi Patel' });
}
}This works, but reassignment is still the better default. It works the same for tracked and plain fields. It also behaves the same whether the array came from a parent, a wire, or your own code. @track wraps the value in a proxy, which can surprise code that compares objects or passes them to non-LWC libraries. Use it when you have a deeply nested structure that you need to edit in place.
Debugging a list that does not update
- The data changed but the screen did not. Check whether the handler mutated the array in place. Look for
push,splice,sort,reverse, or an assignment to an element's property. Replace it with an operation that returns a new array and assign the result. - The screen updates after an unrelated action. The in-place mutation did happen. Some other change then caused a render, and the template read the already-changed array. This is the signature of a missed reassignment.
- A "read-only" or proxy error appears. The array came from
@apior@wire. Copy it before changing it. - Inputs or child components show the wrong data after a sort or removal. The keys are index-based or duplicated. Switch to a stable unique
Id. - A console warning about keys. An item is missing a
key, thekeyis not on the first element inside the iteration template, or two items share a key.
Exercise
A handler runs this.contacts.splice(index, 1) to remove a row, and the row stays on screen. Rewrite the handler so the row disappears, and explain why your version works. Assume contacts is a plain field and each contact has an Id.
Show answer
Use filter and assign the result: this.contacts = this.contacts.filter((contact) => contact.Id !== id);, with id read from event.currentTarget.dataset.id. splice changes the existing array in place, so the field still holds the same array and LWC sees no change. filter returns a new array, and assigning it to the field is what schedules the re-render. The key (contact.Id) lets the engine remove only the element for the missing item and keep the others.
Exercise
A list of rows uses key={position} from for:index. Each row has a text input. The user types "hello" into the first row's input, then clicks a button that sorts the list alphabetically. Afterward, the "hello" text is still in the first row's input, but the first row now shows a different contact. Why, and what is the fix?
Show answer
With index keys, key 0 is still present after the sort, so the engine reuses the first element and only rewrites its displayed text. The input inside that element is not recreated, so its typed value stays and now sits beside a different contact. The fix is to use a stable, unique identifier from the data, such as key={contact.Id}. Then the sort moves each element, input included, to its new position along with its contact.
Exercise
Your child component receives @api items from a parent and calls this.items.push(newItem). What happens, and how do you add an item correctly?
Show answer
The call throws an error, because values passed through @api are read-only in the child. Copy the data into a private field in a setter, for example this._items = value.map((item) => ({ ...item })), and add with this._items = [...this._items, newItem]. Alternatively, dispatch a custom event so the parent updates the data it owns.