Sub topic 5
Observing nested changes with @track
This chapter covers what @track adds to the reactivity you already have, how it works, and where it stops working. It assumes you know modern JavaScript (classes, spread syntax) and the structure of a Lightning web component (HTML, JS, and meta files). It also assumes you understand the difference between a primitive value and an object reference. The previous chapters showed that every class field is reactive and that reassigning a field triggers a rerender. Here we deal with the case reassignment does not cover cleanly: changing something inside an object or array that a field holds.
The problem: a change the component cannot see
A plain field is observed by its value. When you write this.count += 1, the field gets a new value, and the component schedules a rerender if the template used count. When a field holds an object, its value is a reference to that object. Changing a property inside the object leaves the reference the same.
import { LightningElement } from 'lwc';
export default class PlainProfile extends LightningElement {
profile = { name: 'Ada', city: 'London' };
rename() {
// The object changes, but the field still points to the same object.
this.profile.name = 'Grace';
}
}<template>
<lightning-button label="Rename" onclick={rename}></lightning-button>
<p>Name: {profile.name}</p>
</template>After rename() runs, the paragraph still shows "Ada". The field profile was not reassigned, and a plain field does not look inside the object it holds. The data changed, but the component was never told.
There are two ways to fix this. The first is to reassign the field with a new object:
import { LightningElement } from 'lwc';
export default class ProfileCard extends LightningElement {
profile = { name: 'Ada', city: 'London' };
rename() {
this.profile = { ...this.profile, name: 'Grace' };
}
}The second is @track, which is the subject of this chapter.
What @track does
@track is a decorator you place on a field. It tells the framework to observe the contents of the object or array the field holds, in addition to the field itself.
import { LightningElement, track } from 'lwc';
export default class TrackedProfile extends LightningElement {
@track profile = { name: 'Ada', city: 'London' };
rename() {
this.profile.name = 'Grace';
}
}Now the same one-line mutation works. The template that reads profile.name rerenders after rename() runs.
The import matters. track is a named export from lwc, so you must add it to the import statement, as in import { LightningElement, track } from 'lwc';. Forgetting this produces a compile error.
How it works internally
When a field is decorated with @track, the framework does not hand your code the original object. It wraps the value in a proxy, a JavaScript object that intercepts property reads and writes. The proxy does two jobs:
- On a read, it records that the current render used that property.
- On a write, it checks whether a previous render used that property. If so, it schedules a rerender of the component.
This is why @track is described as observing nested changes. The observation is also scoped to what the template actually used. If a template reads only profile.name and your code changes profile.city, the template did not depend on city, so no rerender is needed for it.
The wrapping applies deeply. If profile held an address object with a street property, a template that reads profile.address.street would also rerender when you change this.profile.address.street.
Arrays
Arrays work the same way. A plain field holding an array is observed only when you reassign it. A tracked array also observes element changes and mutating methods such as push, splice, and sort.
import { LightningElement, track } from 'lwc';
export default class TodoList extends LightningElement {
@track items = [
{ id: 1, label: 'Write chapter', done: false },
{ id: 2, label: 'Review chapter', done: false }
];
addItem() {
const nextId = this.items.length + 1;
this.items.push({ id: nextId, label: `Task ${nextId}`, done: false });
}
toggleFirst() {
this.items[0].done = !this.items[0].done;
}
}<template>
<lightning-button label="Add" onclick={addItem}></lightning-button>
<lightning-button label="Toggle first" onclick={toggleFirst}></lightning-button>
<ul>
<template for:each={items} for:item="item">
<li key={item.id}>{item.label}: {item.done}</li>
</template>
</ul>
</template>Both push and the nested write this.items[0].done = ... cause a rerender. Notice that toggleFirst changes a property of an object inside an array. The proxy wraps nested plain objects too, so this is observed as well.
Without @track, you would write the same operations as reassignments:
addItem() {
const nextId = this.items.length + 1;
this.items = [...this.items, { id: nextId, label: `Task ${nextId}`, done: false }];
}
toggleFirst() {
this.items = this.items.map((item, index) =>
index === 0 ? { ...item, done: !item.done } : item
);
}Both styles are valid. Choose one per field and stay with it.
What @track does not observe
@track has boundaries. Knowing them prevents the most common confusion with the decorator.
Only plain objects and arrays are wrapped
The proxy is created for plain objects (created with {} or Object.create(null)) and arrays. Other kinds of values are left alone:
Date,Map,Set, andPromiseinstances- Instances of your own classes
- DOM elements and functions
A change inside one of these does not trigger a rerender, even under @track.
import { LightningElement, track } from 'lwc';
export default class DateExample extends LightningElement {
@track deadline = new Date(2026, 11, 31);
shift() {
// Not observed: Date is not a plain object.
this.deadline.setDate(1);
}
shiftObserved() {
// Observed: the field is reassigned.
const next = new Date(this.deadline);
next.setDate(1);
this.deadline = next;
}
}Reassignment always works, no matter what the field holds. @track only extends observation, and it never replaces the reassignment rule.
Only template-used properties cause rerenders
A write rerenders the component only if the last render read that property, either directly in the template or through a getter the template calls. If you mutate a tracked property that no template expression reads, nothing happens, and that is the correct behavior.
Tracked values are proxies, not the original objects
Because this.profile returns a proxy, a few surprises follow:
- Strict equality with the original object fails. If you keep a reference to the object you assigned,
this.profile === originalisfalse. - Passing the value to a child through an
@apiproperty gives the child a read-only view. The child cannot mutate it (a later chapter explains why). - Some libraries and platform APIs do not like proxies. If you need a plain copy, create one with
JSON.parse(JSON.stringify(this.profile))or a structured clone of a copied object. Each approach has its limits: JSON drops functions andundefinedvalues and turns dates into strings.
Do you still need @track?
Since the Spring '20 release, all fields are reactive, and @track is needed only for the in-place mutation case described above. Before that release, you had to decorate every field you wanted to observe, which is why older code and blog posts use @track everywhere. In current code, an @track on a primitive field does nothing useful.
import { LightningElement, track } from 'lwc';
export default class Redundant extends LightningElement {
// Unnecessary: primitives are already reactive.
@track count = 0;
// Also unnecessary if you only ever reassign the field.
@track settings = { theme: 'dark' };
}Use these rules:
| Situation | Approach |
|---|---|
| Field holds a primitive | Plain field, reassign |
| Field holds an object or array and you replace it with a new one | Plain field, reassign |
| Field holds a plain object or array and you edit it in place | `@track` |
| Field holds a `Date`, `Map`, `Set`, or class instance | Plain field, reassign with a new instance |
Reassignment has one practical advantage. Each update produces a new value, so you can compare old and new, and the data flow is easier to follow. In-place mutation with @track is shorter when you edit deep structures, for example a form object with many nested fields.
Common mistakes
- Mutating a plain field and expecting a rerender. If
this.profile.name = 'Grace'does nothing on screen, check whetherprofilehas@track, or switch to reassignment. - Forgetting the import. Using
@trackwithout importingtrackfromlwcfails to compile. - Tracking a class instance. The decorator does not observe its internals. Reassign instead, or expose the data as plain fields on a plain object.
- Comparing proxies to originals. Compare by a key such as
id, not by object identity. - Mutating through a stale reference. Always go through
this.field. - Decorating everything. Excess
@trackhides which fields are edited in place and misleads readers.
Exercise
A component declares profile = { name: 'Ada', city: 'London' }; with no decorator. A button handler runs this.profile.city = 'Paris';, and the template shows {profile.city}, but the page still shows "London". Give two different fixes, and say which one you would choose if the handler is the only place the object is ever edited.
Show answer
Fix 1: add @track (importing track from lwc) so the in-place write this.profile.city = 'Paris' is observed. Fix 2: reassign the field with a new object, this.profile = { ...this.profile, city: 'Paris' };, which needs no decorator. Both work. With a single, shallow edit site, reassignment is the better choice because it needs no extra import or decorator and makes each update a new value.
Exercise
Which of these tracked fields will NOT rerender the template when the handler runs, and why? (a) @track list = [1, 2] with this.list.push(3), (b) @track tags = new Set() with this.tags.add('lwc'), (c) @track form = { user: { email: '' } } with this.form.user.email = '[email protected]'.
Show answer
(b) does not rerender. A Set is not a plain object or array, so @track does not wrap it and add is not observed. To update the display, reassign the field, for example this.tags = new Set([...this.tags, 'lwc']);. (a) works because tracked arrays observe push. (c) works because the proxy wraps nested plain objects, as long as the template reads form.user.email.