Sub topic 2
Every field is reactive
This chapter explains the rule that drives Lightning web component (LWC) rendering: every class field is reactive. It assumes you know modern JavaScript classes and spread syntax, basic HTML templates, and the file layout of a component (HTML, JS, and meta files). It also assumes you know the difference between a primitive value and an object reference. The chapter builds the model that later chapters use for @track and @api.
What "reactive" means here
A field is a variable declared in the body of a component class:
import { LightningElement } from 'lwc';
export default class Counter extends LightningElement {
count = 0;
increment() {
this.count += 1;
}
}The template that pairs with it reads count:
<template>
<lightning-button label="Add one" onclick={increment}></lightning-button>
<p>Count: {count}</p>
</template>Each click runs increment, which assigns a new value to this.count. The framework notices the assignment and renders the component again, so the paragraph shows the new number. You wrote no code to make that happen.
Reactive means the framework watches the field and schedules a rerender when its value changes and the template depends on it.
The old rule and the current rule
Older LWC code marks fields with @track to make them reactive. That was required in early releases. Since the Spring '20 release, all fields are reactive, so a plain field needs no decorator for this. You will still see @track in older code, and a later chapter covers the one job it still does.
How the framework decides to rerender
LWC does not rerender on every assignment. It rerenders when both of these are true:
- The field was read while the template was rendering. This includes reads made through a getter the template calls.
- The field's value changed.
The first condition means the framework builds its watch list from the previous render. A field the template never touched has no effect on the output, so changing it costs nothing.
The second condition means a primitive field must receive a different value. Assigning 5 to a field that already holds 5 does nothing.
The decision looks like this:
Fields the template does not read
Consider a component that records when a timer started but only displays the elapsed time:
import { LightningElement } from 'lwc';
export default class Stopwatch extends LightningElement {
startedAt = 0;
elapsed = 0;
start() {
this.startedAt = Date.now();
}
stop() {
this.elapsed = Date.now() - this.startedAt;
}
}<template>
<lightning-button label="Start" onclick={start}></lightning-button>
<lightning-button label="Stop" onclick={stop}></lightning-button>
<p>Elapsed: {elapsed} ms</p>
</template>Clicking Start changes startedAt, but the template never reads it, so no rerender occurs. Clicking Stop changes elapsed, which the template does read, so the paragraph updates.
This is useful. You can keep working state in fields without paying for a render each time it changes. You do not need a special "non-reactive" mechanism, because a field is only as reactive as the template makes it.
Updates are batched
A rerender does not happen in the middle of your method. The framework schedules it and runs it after the current JavaScript task finishes. Several changes in one method produce one render:
import { LightningElement } from 'lwc';
export default class BatchDemo extends LightningElement {
count = 0;
addThree() {
this.count += 1;
this.count += 1;
this.count += 1;
// The template still shows the old number here.
// After the method returns, one render shows the final value.
}
}Two practical consequences follow:
- The DOM does not update synchronously after an assignment. If you read the rendered output on the next line, you get the old content.
- Intermediate values are never shown. If a field goes from 0 to 1 to 2 to 3 in one method, the user sees 0 and then 3.
If you need to act on the new DOM, use the renderedCallback lifecycle hook, which runs after a render.
Getters follow fields
A getter in the class can combine fields into a derived value. The template can call the getter like a field:
import { LightningElement } from 'lwc';
export default class Totals extends LightningElement {
price = 10;
quantity = 2;
get total() {
return this.price * this.quantity;
}
addOne() {
this.quantity += 1;
}
}<template>
<p>Total: {total}</p>
<lightning-button label="Add one" onclick={addOne}></lightning-button>
</template>The template reads total, and the getter reads price and quantity. All of those reads happen during the render, so the framework watches both fields. Changing quantity rerenders the component and the getter runs again. There is no need to store total in a field and keep it in sync by hand, which is where stale values come from.
Template expressions are deliberately limited. You write {total}, not {price * quantity}. Put any computation in a getter.
Declare your fields
Only fields declared in the class body are reactive. A property you create by assigning to this inside a method is just a plain JavaScript property:
import { LightningElement } from 'lwc';
export default class Greeting extends LightningElement {
// message is never declared as a field
connectedCallback() {
this.message = 'Hello';
}
}The framework has no record of message as a field, so you cannot count on changes to it updating the template. The fix is to declare it, even without an initial value:
import { LightningElement } from 'lwc';
export default class Greeting extends LightningElement {
message;
connectedCallback() {
this.message = 'Hello';
}
}message; creates a field whose value starts as undefined. Declaring every field you assign also makes the component easier to read, because the class lists its state in one place.
Fields are private by default
A field belongs to its own component. A parent component cannot read or set a child's plain field, and the parent's template cannot bind to it. Reactive does not mean public. To let a parent set a value, you need the @api decorator, which a later chapter covers.
The reverse is also true. A reactive field changes only because of code inside the component that owns it, or because a parent set an @api property. Data does not flow into a plain field from outside.
Objects and arrays: the next question
Everything above used primitive values: numbers, strings, and booleans. Primitives change only by reassignment, so the rule is simple. Objects and arrays raise a harder question: what counts as a change when you edit a property inside an object that the field points to?
For now, remember what the framework compares. A field holds a reference, and reassigning the field to a new object is always a change:
import { LightningElement } from 'lwc';
export default class ProfileCard extends LightningElement {
profile = { name: 'Ada', city: 'London' };
rename() {
this.profile = { ...this.profile, name: 'Grace' };
}
}The spread syntax copies the existing properties into a new object, then name overrides one of them. Assigning that new object to this.profile changes the field's value, so a template that reads profile.name rerenders. This works with a plain field and no decorator. The next chapters examine what happens when you edit this.profile.name directly, and when @track is the right tool.
Edge cases worth knowing
- Same primitive value.
this.count = this.countdoes not rerender, because the value did not change. - New object with the same contents.
this.profile = { ...this.profile }is a different reference, so the framework treats it as a change and rerenders. - Fields set before the first render. Assignments in the constructor or in
connectedCallbackare fine. The first render happens after them, and it reads the values you set. - Assignments inside
renderedCallback. A field assignment there can trigger another render, which runsrenderedCallbackagain. If the assignment is unconditional, the result is an infinite loop. Guard such assignments with a flag or a check on the value. - Unused fields. A field the template and its getters never read costs nothing when it changes. It is useful for internal bookkeeping.
Summary of the model
| Situation | Rerender? |
|---|---|
| Field read by the template, new primitive value assigned | Yes |
| Field read by the template, same primitive value assigned | No |
| Field read only by a getter that the template calls, value changed | Yes |
| Field not read during render, value changed | No |
| Object field read by the template, reassigned to a new object | Yes |
| Several assignments in one method | One rerender after the method finishes |
| Property assigned on `this` without a field declaration | Not dependable. Declare the field. |
Exercise
A component declares startedAt = 0; and elapsed = 0;. Its template displays only {elapsed}. A method sets this.startedAt = Date.now();. Does that assignment rerender the component, and why?
Show answer
No. The template never read startedAt during the last render, so the framework has no dependency on it. Only a change to a field that the template or one of its getters reads, such as elapsed, schedules a rerender.
Exercise
A method runs this.count += 1; three times in a row, starting from 0. How many renders occur, and which values can the user see?
Show answer
One render occurs, after the method returns. The user sees 0 before and 3 after. The intermediate values 1 and 2 are never rendered, because updates are batched.
Exercise
A component has price = 10; and quantity = 2;, and the template shows {total}. Write the getter that makes the displayed total update whenever either field changes, and explain why no extra code is needed to keep it current.
Show answer
get total() { return this.price * this.quantity; }. The template reads total, and the getter reads both fields during the render, so the framework tracks them. Changing either field schedules a rerender, and the getter runs again with the new values.