Sub topic 4
Reassigning versus mutating objects and arrays
This chapter assumes you know the structure of a Lightning web component (HTML, JavaScript, and meta files), basic modern JavaScript including spread syntax, and the difference between a primitive value and an object reference.
The rule: the component watches the field, not the contents
Every class field is reactive, but the component only notices when the field itself gets a new value. For a number or a string, any assignment is a new value. For an object or array, the field holds a reference. The component sees a change only when you assign a different reference.
| Action | Example | Rerender without `@track`? |
|---|---|---|
| Reassign a field | `this.profile = { ...this.profile, name: 'Grace' }` | Yes |
| Mutate a property | `this.profile.name = 'Grace'` | No |
| Replace an array | `this.items = [...this.items, item]` | Yes |
| Change an array in place | `this.items.push(item)` | No |
Reassigning an object
Spread syntax copies the existing properties into a new object. Listing name afterward overrides the old value.
import { LightningElement } from 'lwc';
export default class ProfileCard extends LightningElement {
profile = { name: 'Ada', city: 'London' };
rename() {
this.profile = { ...this.profile, name: 'Grace' };
}
}The profile field now points to a new object, so the component rerenders and the template shows the new name. This works without any decorator.
Mutating an object
This version changes the property on the existing object:
import { LightningElement } from 'lwc';
export default class BrokenProfileCard extends LightningElement {
profile = { name: 'Ada', city: 'London' };
rename() {
this.profile.name = 'Grace';
}
}The data changes, but the field still points at the same object. The component sees no new value, so a template reading {profile.name} keeps showing "Ada". If something else later causes a rerender, the template reads the current data and shows "Grace". That makes the bug look intermittent and harder to trace.
Arrays follow the same rule
push, splice, sort, and reverse change an array in place, so none of them trigger a rerender on their own. Build a new array and assign it.
import { LightningElement } from 'lwc';
export default class TaskList extends LightningElement {
tasks = [
{ id: 1, label: 'Write tests' },
{ id: 2, label: 'Review pull request' }
];
nextId = 3;
addTask() {
const task = { id: this.nextId, label: `Task ${this.nextId}` };
this.nextId += 1;
this.tasks = [...this.tasks, task];
}
removeFirst() {
this.tasks = this.tasks.slice(1);
}
sortByLabel() {
this.tasks = [...this.tasks].sort((a, b) => a.label.localeCompare(b.label));
}
}<template>
<lightning-button label="Add" onclick={addTask}></lightning-button>
<lightning-button label="Remove first" onclick={removeFirst}></lightning-button>
<lightning-button label="Sort" onclick={sortByLabel}></lightning-button>
<ul>
<template for:each={tasks} for:item="task">
<li key={task.id}>{task.label}</li>
</template>
</ul>
</template>Note [...this.tasks].sort(...). Calling sort directly on this.tasks would mutate the original array first. Copying before sorting keeps the update a clean reassignment.
Useful non-mutating tools:
[...array, item]orarray.concat(item)to add.array.filter(...)orarray.slice(...)to remove.array.map(...)to change items. Spread the item when you edit it, as in{ ...item, done: true }.[...array].sort(...)to sort.
Shallow copies and nested data
Spread copies only the top level. If profile contained an address object, { ...this.profile } would share that nested address with the old object. Reassigning the top-level field still triggers the rerender. To update a nested value, copy each level on the path to it:
this.profile = {
...this.profile,
address: { ...this.profile.address, city: 'Paris' }
};Exercise
A component has items = ['a', 'b']. A button handler runs this.items.push('c'), and the template loops over items. The list does not update. Rewrite the handler so the list updates, and explain why your version works.
Show answer
Use this.items = [...this.items, 'c'];. Spread creates a new array, and assigning it to the field gives the field a new reference, which the component detects and rerenders. push changed the existing array in place, so the field value never changed.
Exercise
You write this.profile = this.profile; after setting this.profile.name = 'Grace'. Does this rerender the component? What should you write instead?
Show answer
No. The field is assigned the same reference, so there is no new value. Assign a copy: this.profile = { ...this.profile };, or better, build the updated object in a single reassignment.