Sub topic 6
renderedCallback(): working with the rendered DOM
This chapter covers renderedCallback(), the hook that runs after a component's template has been turned into DOM. It assumes you can write a basic Lightning Web Component (an HTML template plus a JavaScript class). It also assumes you know that fields used in a template are reactive, and that you have seen connectedCallback() and render(). The chapter covers when the hook fires, what you can safely do in it, and the mistakes that cause repeated work or infinite render loops.
What renderedCallback() is for
renderedCallback() is called after the component has rendered and the browser DOM reflects the template. The framework calls it on the first render and again after every re-render. That makes it the right place for work that needs real elements:
- Moving focus to an element.
- Measuring an element's size or position.
- Handing a rendered element to a third-party library, such as a chart or a map.
- Reading or setting a DOM property that has no template binding.
Earlier hooks cannot do this work. This table shows what the template contains at each point.
| Hook | Template DOM exists? | `this.template.querySelector()` result |
|---|---|---|
| `constructor()` | No | `null` |
| `connectedCallback()` | No, first render has not happened | `null` on first run |
| `renderedCallback()` | Yes | Returns the element if it is in the template |
A common error is calling querySelector in connectedCallback() and getting null. Move that code to renderedCallback().
It runs after every render
renderedCallback() is not a "once the component is ready" hook. The framework calls it after each render, so any code in it runs again whenever the component re-renders. A component re-renders when a field that the template uses changes, or when a public property that the template uses is set to a new value by the parent.
To run logic only once, guard it with a flag, as in this example.
import { LightningElement } from 'lwc';
export default class FocusInput extends LightningElement {
hasRendered = false;
renderedCallback() {
if (this.hasRendered) {
return;
}
this.hasRendered = true;
const input = this.template.querySelector('input');
if (input) {
input.focus();
}
}
}The matching template is short.
<template>
<label for="name">Name</label>
<input id="name" type="text" />
</template>The flag hasRendered is not used in the template. Because of that, changing it does not trigger a render. If you did use it in the template, setting it inside renderedCallback() would schedule another render. The flag belongs to one instance, so each copy of the component on a page focuses its own input once.
The if (input) check also matters. If the template renders the input conditionally, the element may not exist on the first render. In that case, set the flag only after you find the element, so the code tries again on a later render.
Finding elements in the rendered DOM
Use this.template.querySelector() or this.template.querySelectorAll() to find elements. These methods search only the template of the current component. They do not return elements inside the templates of child components, because each component owns its own DOM. To work with a child, call its public properties and methods.
Two related details:
- Elements that a parent passes into your
<slot>belong to the parent's template. Query them withthis.querySelector(), notthis.template.querySelector(). - Do not call
document.querySelector()to find your own elements. It can return elements from other components or fail to find yours. It is also unreliable under the DOM encapsulation that Lightning applies.
If you add elements yourself, for example by setting innerHTML, add the lwc:dom="manual" attribute to the container element in the template. Without it, the framework does not allow the insertion. Manually added content is also not tracked by the template, so you are responsible for updating it.
<template>
<div class="chart-host" lwc:dom="manual"></div>
</template>Render loops
The most serious renderedCallback() error is changing reactive state that the template uses. The change triggers a re-render, the re-render calls renderedCallback() again, and the cycle repeats. The browser tab can freeze.
This is the loop:
This component loops forever.
import { LightningElement } from 'lwc';
export default class RenderCounter extends LightningElement {
renderCount = 0;
renderedCallback() {
// The template displays {renderCount}, so this schedules another render.
this.renderCount = this.renderCount + 1;
}
}There are three ways to avoid the loop.
- Do not change template fields in
renderedCallback(). Compute values in getters instead, and leaverenderedCallback()for DOM work. - Store bookkeeping values in fields that the template does not use. Changing those fields does not cause a render.
- If you must update a template field, do it only when the value has actually changed. The change then settles after one extra render.
Option 3 looks like this.
import { LightningElement } from 'lwc';
export default class PanelMeasure extends LightningElement {
panelHeight = 0;
renderedCallback() {
const panel = this.template.querySelector('.panel');
if (!panel) {
return;
}
const height = panel.offsetHeight;
if (height !== this.panelHeight) {
this.panelHeight = height;
}
}
}<template>
<div class="panel">
<slot></slot>
</div>
<p>Panel height: {panelHeight}px</p>
</template>On the first render, panelHeight is 0 and the panel is taller, so the field is updated and the component renders once more. On that second pass the heights match, nothing changes, and the loop ends. The comparison is what makes this safe. If the measurement could keep changing between renders, for example because the displayed number changes the layout, this approach could still loop, so test it with realistic content.
Do not repeat expensive work
Even without a loop, renderedCallback() can do too much. Suppose the component creates a chart in it and the component re-renders ten times. Without a guard you create ten charts. Use one of these patterns:
- A boolean flag, as in the focus example, for work that should happen once.
- A check for the specific condition that requires the work, for example "the data changed since last time".
- A stored reference to the object you created, so later renders update it instead of building a new one.
Loading a third-party script is a typical case. loadScript() returns a promise, and you should call it once. Keep an isLibraryLoaded style flag (not used in the template) and set it when the promise resolves, or when you start the load, so a second render does not start it again. A failed load needs a way to reset the flag if you want to retry.
Order across parent and child components
When a parent renders a child, the child's template is rendered as part of the parent's render. As a result, renderedCallback() runs on the child first and on the parent last. For a parent that contains one child, the order of the first render is:
- Parent
constructor(). - Parent
connectedCallback(). - Parent
render(). - Child
constructor(). - Child
connectedCallback(). - Child
render(). - Child
renderedCallback(). - Parent
renderedCallback().
By the time the parent's renderedCallback() runs, the child's DOM is already rendered. The parent still cannot reach into the child's template. It can read the child's public properties or call its public methods.
A re-render of the parent does not always re-render the child. A child re-renders only if something it uses changed, such as a public property the parent passed in with a new value. So a parent's renderedCallback() can fire many times while a child's fires once.
Reading values that were just changed
Code that changes a field in an event handler does not see the DOM update immediately. The framework batches changes and renders later, in a microtask. If you need to act on the updated DOM after a change, do it in renderedCallback(), not in the handler right after the assignment.
This is a common pattern for "show an input, then focus it". The handler sets a flag field such as isEditing = true. The template renders the input when the flag is true. A guard in renderedCallback() then focuses the input.
import { LightningElement } from 'lwc';
export default class EditableLabel extends LightningElement {
isEditing = false;
needsFocus = false;
startEdit() {
this.isEditing = true;
this.needsFocus = true;
}
renderedCallback() {
if (this.needsFocus) {
const input = this.template.querySelector('input');
if (input) {
input.focus();
this.needsFocus = false;
}
}
}
}<template>
<template lwc:if={isEditing}>
<input type="text" />
</template>
<template lwc:else>
<button onclick={startEdit}>Edit</button>
</template>
</template>needsFocus is not used in the template, so changing it never schedules a render. It is a request that renderedCallback() fulfils on the next render and then clears. This keeps focus from jumping back to the input on every later render.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `querySelector` returns `null` | The code runs in `connectedCallback()` or before the element is rendered | Move it to `renderedCallback()` and check for `null` |
| Browser tab freezes | `renderedCallback()` changes a template field every time | Guard the change, or use a field the template does not read |
| Chart or widget is created many times | No once-only guard | Add a flag or store a reference |
| Focus keeps jumping to one input | Focus logic runs on every render | Use a one-shot flag such as `needsFocus` |
| Cannot find a child's inner element | `this.template` does not cross into child templates | Use the child's public API |
| `innerHTML` insertion is rejected or lost | Container is missing `lwc:dom="manual"` | Add the attribute to the container |
Exercises
Exercise
A component sets this.total = this.items.length inside renderedCallback(), and the template displays {total}. What happens, and how would you fix it?
Show answer
The assignment changes a field the template uses, so each render schedules another render, and the tab can freeze in a render loop. Replace the field with a getter such as get total() { return this.items.length; }, so no assignment happens in the hook. Alternatively, only assign when the value differs from the current one.
Exercise
A parent component contains one child. In what order do the two renderedCallback() methods run on the first render, and why?
Show answer
The child's runs first and the parent's runs last. The child's template is rendered as part of the parent's render, so the child finishes rendering before the parent does.
Exercise
You call this.template.querySelector('canvas') in connectedCallback() and get null. Why, and where should the code go?
Show answer
In connectedCallback() the component has not rendered yet, so the canvas is not in the DOM. Move the code to renderedCallback(), check that the element is not null, and use a flag so setup runs only once.