Sub topic 4
Reactive fields: what triggers a re-render
This chapter assumes you can write a basic Lightning Web Component (LWC) bundle with an HTML template and a JavaScript class. It also assumes you know how to bind a property with { }. Here you will learn exactly which changes make the template render again and which ones are silently ignored.
What "reactive" means
A field is a property declared directly in the component class body, such as count = 0;. In current LWC versions, every field is reactive. When the component renders, the engine records which fields the template, and any getters it calls, read. If one of those fields later receives a new value, the engine schedules a re-render of that component.
You do not call a refresh function or a setter. You assign to the field, and the engine does the rest.
<!-- counter.html -->
<template>
<p>Count: {count}</p>
<button onclick={increment}>Add one</button>
</template>// counter.js
import { LightningElement } from 'lwc';
export default class Counter extends LightningElement {
count = 0;
increment() {
this.count += 1;
}
}Each click reassigns this.count. The engine sees that the template read count during its last render, so it renders again and the paragraph shows the new number.
Older code and older tutorials use @track on every field or a decorator-free field that was not reactive. That changed in the Spring '20 release. Today @track has a narrow job, covered below.
The trigger: reassignment to a different value
The engine watches for assignment of a value to the field. Two conditions must both hold for a re-render:
- The field was read during the last render of this component.
- The new value is not identical to the old value.
The diagram shows the path from a change to the screen.
Fields the template never reads
A field that no template expression or getter reads has no effect on rendering. This is useful for internal bookkeeping.
// clickLogger.js
import { LightningElement } from 'lwc';
export default class ClickLogger extends LightningElement {
clicks = 0;
lastClickTime;
handleClick() {
this.lastClickTime = Date.now();
this.clicks += 1;
}
}<!-- clickLogger.html -->
<template>
<button onclick={handleClick}>Click</button>
<p>Clicks: {clicks}</p>
</template>Changing lastClickTime alone never causes a render, because the template does not read it. Changing clicks does. Both assignments run in the same handler, so the single render that follows shows the new clicks value.
The rule is based on what was read, not on what is declared. If a getter reads a field and the template calls that getter, the field counts as read. A field read only inside an event handler does not count.
Assigning the same value
If you assign a value that is identical to the current one, nothing happens.
this.count = 5;
this.count = 5; // no second render, and the first one only if count was not already 5Comparison is by identity, as with ===. For primitives (numbers, strings, booleans), that means equal values. For objects and arrays, it means the same reference. Assigning a new array that holds the same items is a different value, so it does trigger a render.
Mutating objects and arrays
This is the most common source of "my template does not update" bugs. A plain field holding an object or array is only reactive at the level of the field itself. Changing something inside the object does not reassign the field.
// profile.js
import { LightningElement } from 'lwc';
export default class Profile extends LightningElement {
address = { city: 'Paris' };
moveToLyon() {
this.address.city = 'Lyon'; // the field still holds the same object
}
}<!-- profile.html -->
<template>
<p>City: {address.city}</p>
<button onclick={moveToLyon}>Move</button>
</template>After the click, this.address.city is 'Lyon', but the paragraph still shows Paris. The address field was not reassigned, so no change was detected.
You have two ways to fix this.
Option 1: replace the value. Build a new object or array and assign it. This works for any field and makes the change explicit.
moveToLyon() {
this.address = { ...this.address, city: 'Lyon' };
}For arrays, use methods that return a new array.
// shoppingList.js
import { LightningElement } from 'lwc';
export default class ShoppingList extends LightningElement {
items = ['Pen'];
addNotebook() {
this.items = [...this.items, 'Notebook']; // triggers a render
// this.items.push('Notebook'); // would not
}
}Option 2: decorate the field with @track. The decorator makes the engine observe changes inside the value, to any depth.
// profile.js
import { LightningElement, track } from 'lwc';
export default class Profile extends LightningElement {
@track address = { city: 'Paris' };
moveToLyon() {
this.address.city = 'Lyon'; // now observed
}
}@track only observes plain objects and arrays. Instances of classes, Date, Map, and Set are not made deeply reactive. For those, replace the field value.
Which option should you choose? Replacing the value is the default recommendation. It works the same for every type, it makes each change visible in the code, and it matches how data arrives from parents and from Apex or wire adapters. Use @track when a deeply nested structure is edited in many places and rebuilding it each time would be clumsy.
Rendering is batched
Assigning a field does not render immediately. The engine queues the component and renders once the current JavaScript task finishes. Several assignments in one handler therefore produce one render.
// stepper.js
import { LightningElement } from 'lwc';
export default class Stepper extends LightningElement {
step = 1;
label = 'First';
goNext() {
this.step = 2;
this.label = 'Second';
this.step = 3;
}
}The template renders once, with step as 3 and label as 'Second'. The intermediate value 2 is never shown. This also means that code right after an assignment sees the old DOM. If you need to read the DOM after an update, do it in renderedCallback().
Be careful with assignments inside renderedCallback(). If you change a field the template reads, you cause another render, which calls renderedCallback() again. Guard such code with a flag so it does not loop.
Getters are tracked through their fields
A getter has no state of its own. When the template calls it, the fields it reads are recorded as part of the render. Changing any of them re-renders the component.
// orderSummary.js
import { LightningElement } from 'lwc';
export default class OrderSummary extends LightningElement {
quantity = 3;
unitPrice = 4.5;
get total() {
return this.quantity * this.unitPrice;
}
addOne() {
this.quantity += 1; // `total` is recalculated on the next render
}
}You never notify the template that total changed. Reassigning quantity is enough, because the render that reads total also reads quantity. This is why derived values belong in getters and not in extra fields that you must keep in sync by hand.
The same applies to nested reads. A getter that reads this.address.city on an untracked object has the same blind spot as the template: reassigning address is detected, mutating city is not.
Public fields and parents
Fields marked @api are reactive in the same way. A parent that reassigns the value it passes down causes the child to render again. The child should not change an @api value it received. Objects passed down from a parent are read-only to the child, so write to a copy if you need to edit.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Object property changes but the text stays the same | Mutation of an untracked object | Assign a new object, or add `@track` |
| `push` on an array does not add a list item | Same reference, no reassignment | `this.items = [...this.items, item]` |
| Field changes, template never changes | The template and getters do not read the field | Bind the field, or read it through a getter |
| Reassigning the same primitive causes no render | Identical value, nothing to update | Expected behavior |
| Component renders endlessly | Field assigned in `renderedCallback()` without a guard | Add a condition or move the logic |
Exercise
A component declares tags = ['news']; and renders {tagCount} through a getter get tagCount() { return this.tags.length; }. A button handler runs this.tags.push('sports');. The displayed count stays at 1. Explain why, and give two ways to make it update.
Show answer
The field tags still holds the same array reference, and push mutates it in place. The engine only detects reassignment of the field (or, with @track, in-place changes), so it never schedules a render. Fix 1: replace the array with this.tags = [...this.tags, 'sports'];. Fix 2: declare the field with @track (imported from lwc) so the in-place push is observed. Replacing the value is the usual choice.
Exercise
A handler sets this.a = 1;, then this.b = 2;, then this.a = 3;, and the template reads both fields. How many renders occur, and what values does the render show?
Show answer
One render, because rendering is batched until the current task finishes. It shows a as 3 and b as 2. The intermediate value 1 is never displayed.