Sub topic 5
What causes a component to render again
This chapter assumes you can write a basic Lightning Web Component (LWC). It also assumes you know that class fields can appear in the template with {expression} syntax, and that connectedCallback() and renderedCallback() exist. You don't need to know how the reactivity system works internally. By the end you will be able to say which changes make a component render again, which changes don't, and why.
The rule in one sentence
A component renders again when a field that its template used during the last render gets a new value.
Three parts of that sentence matter:
- Used during the last render. The framework records which fields the template read, directly or through a getter. Only those fields are watched.
- Gets a new value. The framework compares the old value with the new one. Assigning the same primitive value again does nothing. Assigning a different object reference counts as a new value.
- Renders again. The framework calls
render(), rebuilds the template output, and updates the DOM where it differs. It then callsrenderedCallback().
A re-render does not call constructor() or connectedCallback() again. Those hooks belong to the creation and insertion of the component. The hooks that run on every render are render() and renderedCallback().
What the framework watches
Since the Spring '20 release, every class field is reactive. You no longer need @track to make a primitive field cause a re-render. The watching works like this:
- The framework evaluates the template.
- Each time the template reads a field (or a getter that reads a field), the framework notes the dependency.
- If any of those fields later changes, the component is marked dirty and scheduled to render again.
A field that the template never reads is not watched. You can change it as often as you like without causing a render.
Seeing it happen
The following component has two counters. Only count appears in the template. A third field, renders, counts how many times renderedCallback() has run.
<template>
<button class="inc" onclick={handleCount}>Increment shown count</button>
<button class="hidden" onclick={handleHidden}>Increment hidden count</button>
<p>Count: {count}</p>
</template>import { LightningElement } from 'lwc';
export default class RenderDemo extends LightningElement {
count = 0;
hiddenCount = 0;
renders = 0;
handleCount() {
this.count += 1;
}
handleHidden() {
this.hiddenCount += 1;
}
renderedCallback() {
this.renders += 1;
console.log(`Render #${this.renders}, count=${this.count}, hiddenCount=${this.hiddenCount}`);
}
}When the component first appears, the console shows Render #1. Click the first button and Render #2 appears, because count is read by the template and changed. Click the second button as many times as you like. No new log line appears, because hiddenCount is never read during render.
Note that renderedCallback() writes to renders. This is safe only because renders is not in the template. If you added {renders} to the template, each render would change a watched field and schedule another render. That is the infinite loop covered later in this chapter.
Common triggers
| Cause | Re-renders? | Notes |
|---|---|---|
| Assigning a new primitive to a field the template reads | Yes | Only if the value actually differs |
| Assigning the same primitive again | No | The comparison finds no change |
| Assigning a new object or array reference to a field the template reads | Yes | A new reference counts as a new value |
| Mutating a property of an object or an element of an array in place | Usually no | See the next section |
| Changing a field the template never reads | No | Not a dependency |
| Parent passes a new value to a child's `@api` property | Yes, for the child | If the child's template reads that property |
| A getter's inputs change, and the template reads the getter | Yes | The dependency is on the underlying fields |
| `render()` returns a different template after a state change | Yes | The new template replaces the old one |
| Calling `refreshApex` or a wire service delivering new data | Yes | Because it assigns the wired property |
Objects and arrays: reassign, don't mutate
For plain objects and arrays, the framework observes assignment to the field. It does not observe changes inside the value. This is the most common reason a component "doesn't update".
import { LightningElement } from 'lwc';
export default class TodoList extends LightningElement {
todos = ['Write chapter'];
addBroken() {
// Changes the array in place. The field still holds the same reference.
this.todos.push('Review chapter');
}
addWorking() {
// Creates a new array and assigns it. The field value changes.
this.todos = [...this.todos, 'Review chapter'];
}
}<template>
<button onclick={addBroken}>Add (in place)</button>
<button onclick={addWorking}>Add (new array)</button>
<ul>
<template for:each={todos} for:item="todo">
<li key={todo}>{todo}</li>
</template>
</ul>
</template>addBroken() changes the array contents, but the field still points at the same array. The component does not render again, so the list on screen does not change. The new item appears later only if something else triggers a render, such as a second click on addWorking(). This kind of delayed update is confusing to debug.
The same applies to objects. Writing this.user.name = 'Ana' on a plain object does not trigger a render. Write this.user = { ...this.user, name: 'Ana' } instead.
The @track decorator makes the framework observe nested changes inside an object or array, so in-place mutation also triggers a re-render. Reassigning with a copy is usually the better habit. It works without a decorator, and it makes each change an explicit, visible step.
Getters and derived values
A getter does not store a value. The template calls it during every render, and every field the getter reads becomes a dependency.
import { LightningElement } from 'lwc';
export default class Cart extends LightningElement {
price = 10;
quantity = 1;
get total() {
return this.price * this.quantity;
}
handleMore() {
this.quantity += 1;
}
}<template>
<button onclick={handleMore}>More</button>
<p>Total: {total}</p>
</template>The template reads only total. Because the getter reads price and quantity, changing either field re-renders the component. You don't need to notify the framework that total changed.
Keep getters free of side effects. A getter runs on every render, and the framework decides when renders happen. Code that sets fields or logs inside a getter will run at unpredictable times and can create render loops.
Parent and child re-renders
A parent re-rendering does not automatically re-render each child. A child re-renders when a value passed to one of its @api properties changes, and only if the child's template reads that property (directly or through a getter).
<template>
<c-price-tag amount={price}></c-price-tag>
<button onclick={handleRaise}>Raise price</button>
</template>import { LightningElement } from 'lwc';
export default class PriceParent extends LightningElement {
price = 10;
handleRaise() {
this.price += 1;
}
}When handleRaise() runs, price changes, so the parent renders again. The parent passes the new amount to the child. The child's amount property gets a new value, so the child renders again too. The order of hooks in this situation is covered in the chapter on parent and child hook order.
Inside the child, amount is a public property. The parent owns it, so the child should not assign to it. If the child needs a modified version, it should compute one in a getter or copy it into its own field.
Timing: renders are batched
A change does not render the component immediately. The framework schedules the render to run shortly afterward, after the current code finishes. Several changes in the same block of code produce one render.
handleReset() {
this.count = 0;
this.label = 'Reset';
this.items = [];
// One render happens after this method returns, not three.
}Two practical results follow:
- The DOM does not change in the middle of your method. If you read an element right after setting a field, you still see the old content.
- To work with the updated DOM, use
renderedCallback(). It runs after the update is done.
Render loops
If renderedCallback() changes a field that the template reads, the component renders again, which calls renderedCallback() again, and so on. The loop continues until something stops it.
import { LightningElement } from 'lwc';
export default class LoopingExample extends LightningElement {
height = 0;
renderedCallback() {
// Bug: height is read by the template, so each render schedules another.
this.height = this.template.querySelector('div').offsetHeight + 1;
}
}The fix is one of the following:
- Don't change template-visible state in
renderedCallback()unless the change is guarded by a condition that eventually becomes false. - Compare before writing: assign only if the new value differs from the current one. An unchanged value does not trigger a render.
- Move one-time setup behind a flag, as shown in the earlier chapter on
renderedCallback().
Changing the template with render()
If your component overrides render(), the framework calls it on every render. The method returns the template to use. When a state change makes render() return a different template than before, the framework replaces the old template output with the new one.
Two points matter here:
render()itself must not change state. It runs as part of rendering, so writing fields in it can cause loops.- A change to a field read only by
render()and not by the template might not be watched in the same way as a template read. If your template selection depends on a field, check that the field is also used somewhere that registers it, or test that the swap occurs. A reliable approach is to base the choice on a field that you also display or use in a getter.
Quick debugging checklist
When a component does not update, work through these questions in order:
- Is the field read by the template (or by a getter the template uses)?
- Did the value actually change, by value for primitives and by reference for objects and arrays?
- Did you mutate an array or object in place? If so, assign a new copy.
- Is the changed value a child's
@apiproperty that the child's template never reads? - Are you checking the DOM too early, before the scheduled render has finished?
When a component updates too often, check whether renderedCallback() or a getter writes to a field that the template reads.
Exercise
A component has the field selected = ['a']. The template shows {selected.length}. A button handler runs this.selected.push('b'), and the number on screen stays at 1. Explain why, and give a one-line change to the handler that fixes it without using @track.
Show answer
The field selected still holds the same array reference after push(), so the framework sees no new value and does not schedule a render. Replace the handler body with this.selected = [...this.selected, 'b'];. Assigning a new array changes the field's value, so the component renders again and the template shows 2.
Exercise
In a component, renderedCallback() runs this.counter += 1;. The field counter is not used anywhere in the template. Does this cause an infinite loop? What changes if you add {counter} to the template?
Show answer
Without {counter} in the template, there is no loop. The template did not read counter, so changing it does not schedule a render. After you add {counter} to the template, each change to counter re-renders the component, which calls renderedCallback(), which changes counter again. That is an infinite render loop.