Sub topic 9
Reactivity: how class fields update the UI
This chapter assumes you know the earlier chapters on the component bundle and on templates and data binding. You should also be comfortable with JavaScript classes, getters, and the spread operator. The chapter covers what makes the template redraw, which changes the framework misses, and how to avoid those misses.
The core rule: fields are reactive
In a Lightning Web Component, every class field is reactive. If the template reads a field during rendering and you later assign a new value to that field, the framework schedules a re-render.
// greetingEditor.js
import { LightningElement } from 'lwc';
export default class GreetingEditor extends LightningElement {
name = 'World';
handleChange(event) {
this.name = event.target.value;
}
}<!-- greetingEditor.html -->
<template>
<p>Hello, {name}!</p>
<input type="text" value={name} onchange={handleChange} />
</template>The assignment this.name = ... is the whole mechanism. You do not call setState, and you do not call a render() method. Plain JavaScript has no built-in way to observe a field assignment, so the LWC framework adds this behavior. A web component built by hand with only standard APIs must update its shadow root itself.
Reactivity applies to fields that the template depends on. A field that the template never reads can change without causing a render. This is useful for internal bookkeeping such as timer IDs or caches.
What happens after an assignment
The framework does not update the DOM synchronously on each assignment. It records that the component is dirty and re-renders once, in a microtask, after the current JavaScript task finishes. Several assignments in one handler therefore produce a single re-render.
Three consequences follow from this:
- The DOM is not updated yet on the line after an assignment. Code that reads the rendered DOM right after
this.name = 'x'sees the old markup. - Intermediate values never reach the screen. If a handler sets a field to
1and then to2, only2is rendered. - Assigning a value equal to the current one does nothing. The framework compares the old and new values and skips the render when they match.
Objects and arrays: reassignment versus mutation
A field holding an object or array is reactive to reassignment. Changing something inside the object is a different matter. The framework only observes the field itself, so mutating an element or property goes unnoticed.
// todoList.js
import { LightningElement } from 'lwc';
export default class TodoList extends LightningElement {
items = [
{ id: 1, label: 'Write chapter' },
{ id: 2, label: 'Review chapter' }
];
nextId = 3;
addItem() {
// Reassignment: the template re-renders.
this.items = [...this.items, { id: this.nextId, label: `Task ${this.nextId}` }];
this.nextId += 1;
}
addItemBroken() {
// Mutation: the array is changed, but the field is not reassigned.
this.items.push({ id: this.nextId, label: `Task ${this.nextId}` });
this.nextId += 1;
}
}<!-- todoList.html -->
<template>
<ul>
<template for:each={items} for:item="item">
<li key={item.id}>{item.label}</li>
</template>
</ul>
<button onclick={addItem}>Add</button>
<button onclick={addItemBroken}>Add (mutation)</button>
</template>addItemBroken does change the data. The new item appears the next time something else triggers a render, which makes the bug look intermittent. In addItemBroken, nextId is a number that is reassigned, but the template does not read it, so that assignment causes no render either.
Prefer immutable updates. Build a new array or object and assign it to the field.
| Goal | Mutation (not observed) | Reassignment (observed) |
|---|---|---|
| Add to array | `this.items.push(x)` | `this.items = [...this.items, x]` |
| Remove from array | `this.items.splice(i, 1)` | `this.items = this.items.filter(it => it.id !== id)` |
| Change a property | `this.user.name = 'Ana'` | `this.user = { ...this.user, name: 'Ana' }` |
@track for deep observation
If you need mutations inside an object or array to trigger a render, decorate the field with @track. The framework then wraps the value so it can observe property writes and array changes, including nested ones.
// userCard.js
import { LightningElement, track } from 'lwc';
export default class UserCard extends LightningElement {
@track user = { name: 'Lee', address: { city: 'Oslo' } };
moveToBergen() {
// Observed because the field is decorated with @track.
this.user.address.city = 'Bergen';
}
}@track has limits:
- It observes plain objects and arrays. It does not observe class instances,
Date,Set, orMapcontents. - It only matters for mutation. Reassigning a field always works, with or without
@track. - It adds a proxy layer. The value you read back is the wrapper, not the original object, so identity comparisons against the original can fail.
Computed values with getters
Template expressions cannot contain logic such as {count * 2}. Compute derived values in a getter. A getter is re-evaluated on every render, and the framework tracks the fields it reads. When any of those fields changes, the component re-renders.
// cartSummary.js
import { LightningElement } from 'lwc';
export default class CartSummary extends LightningElement {
prices = [10, 20, 30];
discount = 0;
get total() {
const sum = this.prices.reduce((a, b) => a + b, 0);
return sum - this.discount;
}
applyDiscount() {
this.discount = 5;
}
}<!-- cartSummary.html -->
<template>
<p>Total: {total}</p>
<button onclick={applyDiscount}>Apply discount</button>
</template>Do not store total in its own field and keep it in sync by hand. Two copies of the same data drift apart as soon as one update path is forgotten. A getter has a single source of truth.
Reactivity and public properties
Fields decorated with @api are reactive too. When a parent assigns a new value to a child's public property, the child re-renders if its template uses that value. The reverse is restricted: a child should not assign to its own @api property, and object values passed in from a parent arrive read-only. To change such data, the child dispatches an event and the parent reassigns the value. The chapters on @api and CustomEvent cover that pattern.
Common errors
- Mutating without reassigning.
push,splice, and direct property writes on an untracked field leave the screen stale. Reassign, or use@track. - Writing a field inside a getter. A getter runs during rendering. Assigning a field there tries to trigger another render during the render.
- Assigning fields in
renderedCallbackwithout a guard. Each assignment can cause another render, which callsrenderedCallbackagain. Guard such code with a flag, or avoid it. - Expecting synchronous DOM updates. Read the DOM after the re-render, for example in
renderedCallback, not on the line after the assignment. - Comparing tracked values by identity. A
@trackfield returns a proxy, sothis.user === originalUsercan befalse.
Exercise
A component has the field items = [] with no decorator. A handler runs this.items.push('a'), and the template shows {items.length} through a getter. The screen still shows 0. Give two ways to fix it.
Show answer
The handler mutates the array without reassigning the field, so the framework never sees a change. Fix 1: reassign, as in this.items = [...this.items, 'a']. Fix 2: decorate the field with @track (imported from lwc) so that mutations of the array are observed. Reassignment is the preferred fix.
Exercise
A click handler runs this.count = 1; this.count = 2; this.count = 2; on a field the template displays. How many re-renders are scheduled, and what is displayed?
Show answer
One re-render. The framework batches the assignments and renders once in a microtask. The display shows 2. The last assignment is also a no-op because the value did not change.