Sub topic 3
What actually triggers a rerender
This chapter assumes you can read a Lightning web component's JavaScript class and HTML template, and that you know primitives are compared by value while objects are compared by reference. It covers when a component rerenders. The next chapters build on this for objects, arrays, and the decorators.
The rule
A component rerenders when a field that the template used during its last render gets a new value.
That sentence contains three conditions:
- The thing that changed is a field of the component class.
- The field was read while the template rendered, either directly or through a getter.
- The new value is different from the old one.
If any of the three is false, nothing is rerendered. The sections below take them in turn.
Condition 1: the field must be used by the template
Reactivity in Lightning Web Components (LWC) is tied to rendering. The framework records which fields the template reads as it renders. Only changes to those fields schedule a new render.
import { LightningElement } from 'lwc';
export default class ClickTracker extends LightningElement {
clicks = 0;
lastClickTime;
handleClick() {
this.clicks += 1;
this.lastClickTime = Date.now();
}
}<template>
<lightning-button label="Click" onclick={handleClick}></lightning-button>
<p>Clicks: {clicks}</p>
</template>Both fields change in handleClick, but only clicks appears in the template. Changing clicks causes a rerender. If a handler changed only lastClickTime, nothing would be rerendered. The field still holds the new value, and JavaScript code can read it. The screen just doesn't depend on it.
This is useful. Fields that hold bookkeeping data, such as timers, flags, or cached values, cost nothing in rendering terms as long as the template never reads them.
Getters count as template reads
A template can only reference a property by name. It cannot contain expressions like {price * quantity}. When you need a computed value, you write a getter. The framework tracks the fields that the getter reads while the template renders.
import { LightningElement } from 'lwc';
export default class CartTotal extends LightningElement {
price = 10;
quantity = 1;
get total() {
return (this.price * this.quantity).toFixed(2);
}
addOne() {
this.quantity += 1;
}
}<template>
<p>Total: {total}</p>
<lightning-button label="Add one" onclick={addOne}></lightning-button>
</template>The template never mentions quantity, but the getter total reads it during rendering. Changing quantity therefore triggers a rerender, and the template evaluates total again. A getter that nothing in the template calls does not count. Its fields are not tracked.
Fields read only in a hidden branch
A conditional block that is not rendered is not evaluated, so fields used only inside it are not recorded for that render. This causes no visible problem. Whatever makes the block appear is itself a field the template reads. When that field changes, the component rerenders, evaluates the block, and starts tracking the fields inside it.
Condition 2: the value must actually change
LWC compares the old and new values with strict inequality. Assigning an equal value does nothing.
import { LightningElement } from 'lwc';
export default class StatusBadge extends LightningElement {
status = 'ready';
items = ['a', 'b'];
sameString() {
this.status = 'ready'; // equal primitive: no rerender
}
sameContentNewArray() {
this.items = [...this.items]; // new reference: rerender
}
}| Assignment | Compared as | Rerender? |
|---|---|---|
| `this.count = 5` when `count` is already `5` | primitive value | No |
| `this.name = 'Ada'` when `name` is `'Grace'` | primitive value | Yes |
| `this.items = this.items` | same reference | No |
| `this.items = [...this.items]` | new reference | Yes |
| `this.items.push('c')` on a plain field | no assignment happens | No |
The last row is the main topic of the next chapter. A plain field notices that it was assigned. It does not notice that the object it points to was modified. The array was modified but the field still points to the same array, so there's no change to detect.
Note that the fourth row triggers a rerender even though the contents are identical. The framework compares references, not contents. Creating new objects on every event handler can cause extra renders, so reassign only when something actually changed.
Condition 3: rerenders are batched
Assigning a field does not rerender immediately. It schedules a render. The framework runs it after the current synchronous code finishes, in a microtask. Several changes made in the same handler produce one render.
import { LightningElement } from 'lwc';
export default class BatchDemo extends LightningElement {
first = 'Ada';
last = 'Lovelace';
renderCount = 0;
renderedCallback() {
this.renderCount += 1; // not read by the template, so no extra render
}
swap() {
this.first = 'Grace';
this.last = 'Hopper';
const text = this.template.querySelector('p').textContent;
console.log(text); // still shows the old names
}
}<template>
<p>{first} {last}</p>
<lightning-button label="Swap" onclick={swap}></lightning-button>
</template>Clicking the button changes two fields and produces one render. Two consequences follow:
- Intermediate values are never displayed. If a handler sets a field to
'loading'and then to'done'within the same synchronous run, the user only sees'done'. - The DOM is stale right after an assignment. The
console.logabove prints the old text because the render has not run yet. If you need to read the updated DOM, wait for the render, for example inrenderedCallback, or withawait Promise.resolve()inside anasyncmethod.
What a rerender runs
The diagram shows the path from an assignment to the screen.
A rerender evaluates the template again and updates only the parts of the DOM whose output changed. It does not rebuild the component. In particular:
- The constructor does not run again.
connectedCallbackdoes not run again. It runs when the component is inserted into the DOM.- Field values, including fields the template doesn't use, are kept.
renderedCallbackruns after every render, including the first.
Child components follow the same rule. A child rerenders when one of its own fields changes, or when a parent sets one of its public properties to a different value. A parent rerendering does not force its children to rerender.
A frequent mistake: changing a rendered field in renderedCallback
Because renderedCallback runs after each render, assigning a field that the template reads inside it creates a loop. The assignment schedules a render, the render calls renderedCallback, and it assigns again.
import { LightningElement } from 'lwc';
export default class Greeting extends LightningElement {
label = 'Loading';
initialized = false;
renderedCallback() {
if (this.initialized) {
return;
}
this.initialized = true;
this.label = 'Ready';
}
}<template>
<p>{label}</p>
</template>The guard initialized is a field the template does not read, so setting it costs no render. The component renders once with Loading, sets label, renders again with Ready, and then the guard stops the third pass. If the assignment depended on a value that changes every time, for example this.label = String(Date.now()), the guard would be essential.
Often the better fix is to avoid the second render entirely. Compute the value in a getter, or set it in connectedCallback, which runs before the first render.
Seeing renders for yourself
When you are unsure whether a change causes a render, count them.
import { LightningElement } from 'lwc';
export default class RenderProbe extends LightningElement {
renders = 0;
hidden = 0;
visible = 0;
renderedCallback() {
this.renders += 1;
console.log('Render number', this.renders);
}
bumpHidden() {
this.hidden += 1;
}
bumpVisible() {
this.visible += 1;
}
}<template>
<p>Visible: {visible}</p>
<lightning-button label="Hidden" onclick={bumpHidden}></lightning-button>
<lightning-button label="Visible" onclick={bumpVisible}></lightning-button>
</template>The first button changes hidden, which the template never reads, so the console prints nothing. The second changes visible and prints one line per click. The renders field is incremented in renderedCallback but not shown in the template, so counting does not cause renders itself.
Summary of the model
- Rerenders follow reads. A change matters only if the template read the field in its last render, directly or through a getter.
- Rerenders follow changes. Primitives compare by value and objects compare by reference.
- Rerenders are batched. Many assignments in one synchronous run produce one render, and the DOM is stale until it happens.
- A rerender reevaluates the template and patches the DOM. Constructor and
connectedCallbackare not repeated, andrenderedCallbackruns again.
The reference comparison is why mutating an object or array held in a plain field leaves the screen unchanged. The next chapter builds on this.
Exercise
A component has fields firstName, lastName, and loginCount. The template shows only a getter get fullName() { return this.firstName + ' ' + this.lastName; }. A handler runs this.firstName = 'Grace'; this.lastName = 'Hopper'; this.loginCount += 1;. Which of these changes can cause a rerender, and how many renders happen?
Show answer
firstName and lastName can cause a rerender, because the fullName getter reads them while the template renders. loginCount is not read by the template or the getter, so it does not. The three assignments happen in one synchronous run, so renders are batched and exactly one render happens (assuming at least one of the names had a different value before).
Exercise
A field items holds an array that the template loops over. A handler runs this.items.push('new'), and the screen does not update. A second handler runs this.items = this.items and the screen still does not update. Explain why neither works and give one statement that does.
Show answer
The field is compared by reference. push modifies the array but never assigns the field, so no change is detected. this.items = this.items assigns the same reference, which is equal to the old value, so nothing is scheduled. Assigning a new array does work, for example this.items = [...this.items, 'new'], because the new reference differs from the old one.