Sub topic 10
Changing Objects and Arrays in Place with @track
This chapter assumes you have read the earlier chapters on binding fields with { }, getters, and event handlers. You should know that assigning a new value to a class field re-renders the template. Here you will see what happens when you change the inside of an object or array instead of assigning a new value.
What triggers a re-render
Every class field in a Lightning Web Component is reactive. If the template read a field during its last render and you later assign a different value to that field, the framework schedules a new render.
The check is about assignment. The framework notices that this.name = 'Ada' replaced the old value. It does not automatically notice that something inside the old value changed.
For strings, numbers, and booleans the difference never matters, because you can only replace them. For objects and arrays it matters a great deal.
The in-place mutation problem
Consider a component that shows an address and lets the user press a button to change the city.
<!-- profile.html -->
<template>
<p>City: {address.city}</p>
<button onclick={moveToLyon}>Move to Lyon</button>
</template>// profile.js
import { LightningElement } from 'lwc';
export default class Profile extends LightningElement {
address = { city: 'Paris' };
moveToLyon() {
this.address.city = 'Lyon';
}
}After the click, this.address.city is 'Lyon' in memory. The page still says Paris. The field address still points to the same object, so the framework saw no assignment to address and did not re-render.
The same thing happens with arrays. Calling push, splice, or sort, or assigning this.items[0] = 'x', changes the array without replacing it.
// shoppingList.js
import { LightningElement } from 'lwc';
export default class ShoppingList extends LightningElement {
items = ['Pen', 'Notebook'];
addItem() {
// The array grows, but the template does not update.
this.items.push('Stapler');
}
}Fix 1: assign a new value
The simplest fix is to build a new object or array and assign it to the field. This is an assignment, so the framework sees it.
// profile.js
import { LightningElement } from 'lwc';
export default class Profile extends LightningElement {
address = { city: 'Paris', country: 'France' };
moveToLyon() {
this.address = { ...this.address, city: 'Lyon' };
}
}The spread syntax copies every property of the old object into a new one, and city: 'Lyon' overrides the copied city. For arrays, use the same idea.
// shoppingList.js
import { LightningElement } from 'lwc';
export default class ShoppingList extends LightningElement {
items = ['Pen', 'Notebook'];
addItem() {
this.items = [...this.items, 'Stapler'];
}
removeFirst() {
this.items = this.items.slice(1);
}
sortItems() {
this.items = [...this.items].sort();
}
}Note the copy in sortItems. The sort method sorts the array it is called on, so this.items.sort() would mutate in place. Copying first keeps the change an assignment.
Methods such as map, filter, slice, and concat already return new arrays, so they pair naturally with assignment.
Fix 2: decorate the field with @track
The @track decorator tells the framework to observe the contents of an object or array held by a field. Once a field is tracked, changing a property inside it re-renders the template.
// profile.js
import { LightningElement, track } from 'lwc';
export default class Profile extends LightningElement {
@track address = { city: 'Paris' };
moveToLyon() {
this.address.city = 'Lyon';
}
}The same applies to arrays.
// shoppingList.js
import { LightningElement, track } from 'lwc';
export default class ShoppingList extends LightningElement {
@track items = ['Pen', 'Notebook'];
addItem() {
this.items.push('Stapler');
}
}@track is deep. It also observes nested objects and arrays reachable from the field, such as this.order.customer.address.city or this.order.lines[0].quantity.
How it works
When you read a tracked field, you do not get the original object. You get a proxy, which is a wrapper that forwards reads and writes to the original. The proxy records which properties the template read during rendering. When a write goes through the proxy to one of those properties, the framework schedules a render.
This explains two behaviors:
- Writes must go through the tracked field (
this.address.city = ...). A write through a separate reference to the raw original object bypasses the proxy and is not observed. - Reading a tracked value gives you the proxy, not the original object. The proxy behaves like the original in almost every way, but identity checks against the raw object can surprise you.
What @track does not cover
@track observes plain objects and arrays. It does not observe values created from other classes or built-in collections.
| Value held in the field | Mutation observed with @track? |
|---|---|
| Plain object `{ a: 1 }` | Yes |
| Array `[1, 2, 3]` | Yes |
| Nested plain objects and arrays | Yes |
| `Date` | No. Assign a new `Date` instead. |
| `Map` and `Set` | No. Assign a new collection instead. |
| Instance of your own class | No. Assign a new instance or replace the field. |
For those types, reassignment is the only dependable approach.
// deadline.js
import { LightningElement } from 'lwc';
export default class Deadline extends LightningElement {
due = new Date(2026, 11, 31);
get dueLabel() {
return this.due.toDateString();
}
extendByOneDay() {
// setDate() would mutate in place and the template would not update.
const next = new Date(this.due);
next.setDate(next.getDate() + 1);
this.due = next;
}
}Choosing between reassignment and @track
Reassignment is usually the better default, for three reasons:
- It works for every type, including
Date,Map, andSet. - It does not depend on a decorator that a teammate may remove while tidying a file.
- It avoids the proxy wrapper, which matters when you hand data to code outside LWC.
@track earns its place when state is a deeply nested structure and rebuilding the whole copy for every small edit would be noisy, for example a form model with a nested array of line items. Even then, many teams keep the nested object immutable and rebuild only the changed branch.
Gotchas
A render still needs a reason
A re-render happens only if the template, or a getter it calls, read the changed property during the last render. Mutating a tracked property that nothing displays does nothing visible, and that is correct.
Untracked changes can appear later
An untracked in-place change is not lost. The data in memory is correct. If something else triggers a render, the template shows the new data.
// confusing.js
import { LightningElement } from 'lwc';
export default class Confusing extends LightningElement {
address = { city: 'Paris' };
clicks = 0;
update() {
this.address.city = 'Lyon'; // not observed
this.clicks += 1; // observed, so the page re-renders
}
}If the template shows both {address.city} and {clicks}, the city appears to update, but only because clicks caused the render. Remove the counter and the city stops updating. This kind of bug passes quick manual tests and fails later, so do not rely on it.
Values passed down through @api are read-only
When a parent passes an object or array to a child through an @api property, the child receives a read-only view. Mutating it throws an error in the child. If the child needs to edit the data, it should copy it into its own field and change the copy.
// editableList.js
import { LightningElement, api } from 'lwc';
export default class EditableList extends LightningElement {
_source = [];
working = [];
@api
get source() {
return this._source;
}
set source(value) {
this._source = value;
this.working = [...value];
}
addBlank() {
this.working = [...this.working, ''];
}
}Proxies and third-party code
Tracked values are proxies. Some libraries, and some structured-clone or serialization paths, behave unexpectedly with proxies. When you pass a tracked object to non-LWC code, pass a plain copy. JSON.parse(JSON.stringify(value)) produces one for JSON-safe data.
Do not mutate inside a getter
A getter that sorts this.items in place changes state during rendering, which can cause extra renders or confusing results. Copy first, as in [...this.items].sort(), and return the copy.
Summary of the rules
- Reassigning a field always triggers a re-render, for any value type.
- Changing the inside of a plain object or array triggers a re-render only if the field is decorated with
@track. Date,Map,Set, and class instances are never observed from the inside. Assign a new value.- Prefer building a new value and assigning it. Reach for
@trackwhen nested in-place edits make that impractical.
Exercise
A component has the field cart = { items: [], total: 0 } with no decorator. A method runs this.cart.items.push('Pen'); this.cart.total = 4.5;, and the template shows {cart.total}. The page does not update. Give two ways to fix it.
Show answer
Fix 1: replace the object with a new one, for example this.cart = { items: [...this.cart.items, 'Pen'], total: 4.5 };, because assigning to the field is always observed. Fix 2: decorate the field with @track (@track cart = { items: [], total: 0 };, importing track from 'lwc') so the in-place push and the assignment to total are observed through the proxy.
Exercise
A field holds new Set(['a']) and is decorated with @track. A method calls this.tags.add('b'). Will the template update, and what should the method do instead?
Show answer
It will not update, because @track observes only plain objects and arrays, not Set. The method should create a new set and assign it, for example this.tags = new Set([...this.tags, 'b']);.