Sub topic 4
Reassigning versus mutating objects and arrays
This chapter assumes you can write a basic Lightning web component and read modern JavaScript, including classes and spread syntax. It also assumes you know that an object variable holds a reference to the object, not a copy of it. The earlier chapters covered how fields trigger rerenders. This chapter looks at the case that causes the most confusion: fields that hold objects and arrays.
The core rule
A Lightning web component watches each field for a change of value. For a field that holds an object or array, the value is the reference. The component asks whether the field now points at something different. It does not ask whether something inside the object changed.
- Reassigning the field (
this.profile = {...}) changes the reference, so the template rerenders. - Mutating the contents (
this.profile.name = 'Grace') leaves the reference alone, so a plain field does not rerender.
The data does change in the second case. Only the screen is stale.
A failing example
This component adds a task to an array with push:
import { LightningElement } from 'lwc';
export default class TaskList extends LightningElement {
nextId = 3;
tasks = [
{ id: 1, label: 'Write tests' },
{ id: 2, label: 'Review PR' }
];
addTask() {
// Mutation: same array, new element inside it.
this.tasks.push({ id: this.nextId, label: `Task ${this.nextId}` });
this.nextId += 1;
}
}<template>
<lightning-button label="Add task" onclick={addTask}></lightning-button>
<ul>
<template for:each={tasks} for:item="task">
<li key={task.id}>{task.label}</li>
</template>
</ul>
</template>Clicking the button does nothing visible. this.tasks still points at the same array, so the component sees no change. nextId is a plain number that the template never reads, so it triggers nothing either.
The fix is to build a new array and assign it to the field:
import { LightningElement } from 'lwc';
export default class TaskList extends LightningElement {
nextId = 3;
tasks = [
{ id: 1, label: 'Write tests' },
{ id: 2, label: 'Review PR' }
];
addTask() {
this.tasks = [...this.tasks, { id: this.nextId, label: `Task ${this.nextId}` }];
this.nextId += 1;
}
}The same template now works. The spread syntax copies the existing elements into a new array, appends the new task, and the assignment changes the field's reference.
Why identity is what counts
When you assign to a field, the component compares the new value with the old one using strict equality (===). If they differ, and the template reads that field, the component schedules a rerender. For objects, === compares references, not contents.
This explains a behavior that surprises many developers:
this.tasks.push(newTask);
this.tasks = this.tasks; // same reference, so nothing happensReassigning the same reference does not rerender. You need a different object.
The following diagram shows the decision the component makes.
The stale screen can fix itself by accident
Mutation without reassignment can look like it works some of the time. Suppose you mutate this.profile.name, and later another field that the template reads changes. That second change causes a rerender. The template then reads the current profile.name, and the new name appears.
This makes the bug intermittent. The mutation works whenever something else happens to trigger a render. Don't rely on that. Reassign the field, or use @track (covered in the next chapter).
Updating objects by reassignment
For a flat object, copy it with spread and override what changed:
import { LightningElement } from 'lwc';
export default class ProfileCard extends LightningElement {
profile = { name: 'Ada', city: 'London' };
rename() {
this.profile = { ...this.profile, name: 'Grace' };
}
}<template>
<lightning-button label="Rename" onclick={rename}></lightning-button>
<p>{profile.name} lives in {profile.city}.</p>
</template>The template reads profile.name. Reassigning profile rerenders the component, and the expression is evaluated again against the new object.
Spread copies only one level
Spread is a shallow copy. Nested objects are copied by reference, so the old and new objects share them. To change a nested value, copy every level on the path to it:
import { LightningElement } from 'lwc';
export default class AccountCard extends LightningElement {
account = {
name: 'Acme',
address: { city: 'London', country: 'UK' }
};
moveToParis() {
this.account = {
...this.account,
address: { ...this.account.address, city: 'Paris' }
};
}
}If you wrote this.account = { ...this.account } and then set this.account.address.city = 'Paris', you would mutate the object that the old and new copies both share. The top-level reference changes, so the component rerenders. The old object is also corrupted, which causes trouble if you saved it for an undo feature or a comparison.
Updating arrays by reassignment
Array methods fall into two groups. Some change the array in place. Others return a new array and leave the original alone. For a plain field, use the second group, or copy first.
| Goal | Mutating form (no rerender on a plain field) | Reassigning form |
|---|---|---|
| Add to the end | `this.items.push(x)` | `this.items = [...this.items, x]` |
| Add to the start | `this.items.unshift(x)` | `this.items = [x, ...this.items]` |
| Remove by id | `this.items.splice(i, 1)` | `this.items = this.items.filter(t => t.id !== id)` |
| Replace one element | `this.items[i] = x` | `this.items = this.items.map(t => t.id === id ? x : t)` |
| Update a property of one element | `item.done = true` | `this.items = this.items.map(t => t.id === id ? { ...t, done: true } : t)` |
| Sort | `this.items.sort(fn)` | `this.items = [...this.items].sort(fn)` |
| Reverse | `this.items.reverse()` | `this.items = [...this.items].reverse()` |
| Clear | `this.items.length = 0` | `this.items = []` |
sort and reverse are easy to miss because they return the array and look like pure functions. They mutate the array they are called on. Copy first, then sort the copy.
Here is a fuller component that combines several of these operations:
import { LightningElement } from 'lwc';
export default class TodoBoard extends LightningElement {
nextId = 3;
todos = [
{ id: 1, label: 'Write tests', done: false },
{ id: 2, label: 'Review PR', done: false }
];
addTodo() {
const todo = { id: this.nextId, label: `Task ${this.nextId}`, done: false };
this.nextId += 1;
this.todos = [...this.todos, todo];
}
toggle(event) {
const id = Number(event.target.dataset.id);
this.todos = this.todos.map(t => (t.id === id ? { ...t, done: !t.done } : t));
}
remove(event) {
const id = Number(event.target.dataset.id);
this.todos = this.todos.filter(t => t.id !== id);
}
}<template>
<lightning-button label="Add" onclick={addTodo}></lightning-button>
<ul>
<template for:each={todos} for:item="todo">
<li key={todo.id}>
{todo.label} ({todo.done})
<button data-id={todo.id} onclick={toggle}>Toggle</button>
<button data-id={todo.id} onclick={remove}>Remove</button>
</li>
</template>
</ul>
</template>Each handler produces a new array, so each one rerenders. toggle also creates a new object for the changed item, which keeps the old item intact.
Edge cases
- Reading a field is not a change. Calling
this.items.map(...)orthis.items.filter(...)and discarding the result does nothing. These methods return new arrays and do not change the field. - Local variables. You can mutate freely on a local copy before assigning it. This is a common way to batch several edits into one rerender:
applyEdits() {
const next = [...this.todos];
next[0] = { ...next[0], done: true };
next.push({ id: this.nextId, label: 'Extra', done: false });
this.nextId += 1;
this.todos = next; // one assignment, one rerender
}- Several assignments in one handler. Rerendering is batched. If you assign
this.todosthree times in one handler, the template renders once afterward, with the final value. - Data from
@wireor a parent. Objects that arrive from a wire service or through an@apiproperty may be read-only. Mutating them can throw an error or silently do nothing. Copying them with spread before changing them avoids both problems. The chapter on one-way data flow explains why. - Class instances, Dates, Maps, and Sets. Reassignment works for any value. Mutating a
Mapor aDatein place is just as invisible to a plain field. If you must keep one, create a new instance and assign it.
Checking your understanding of cost
Copying creates garbage. For lists of a few hundred items this does not matter. For very large collections, repeated copying inside a loop can become slow. Build the new array once, outside the loop, and assign it once. Prefer one map or filter over a loop that reassigns on every pass.
Exercise
A component has the field cart = { items: [], total: 0 } and the template displays {cart.total}. A handler runs this.cart.total = 25; and the screen still shows 0. Write the one-line change that makes the screen update without using @track.
Show answer
Reassign the field with a new object: this.cart = { ...this.cart, total: 25 };. The original line changed the property inside the same object, so the reference stayed the same and the plain field saw no change. The spread creates a new object, and the assignment changes the field's reference, which triggers the rerender.
Exercise
A handler runs this.names = this.names.sort(); on a plain field holding an array of strings. Explain what is wrong with this code, and rewrite it to be safe.
Show answer
sort mutates the original array in place and returns that same array. The assignment therefore stores the same reference, so there is no reference change for the component to detect. The order changes in the data, but the screen may not refresh. It also changes the array that other code may be holding. Copy first and assign the result: this.names = [...this.names].sort();.
Exercise
A component holds settings = { theme: { color: 'blue', size: 12 }, lang: 'en' }. Write a statement that changes only size to 14 by reassignment and keeps color and lang.
Show answer
this.settings = { ...this.settings, theme: { ...this.settings.theme, size: 14 } };. Each level on the path to size is copied, so the new object shares no mutated parts with the old one.