Sub topic 6
renderedCallback(): working with the rendered DOM
This chapter assumes you can write a Lightning Web Component (LWC) with an HTML template and a JavaScript class. It also assumes you know reactive properties, template expressions, and basic DOM events. You should already know that connectedCallback() runs when the component is inserted.
What renderedCallback() does
renderedCallback() is a lifecycle hook that runs after the component has rendered. The DOM that the template produced exists at this point, so you can read it, measure it, or move focus into it.
The hook runs after the first render and after every re-render. A re-render happens when a reactive value used by the template changes. Many beginners miss this. Code that belongs to the first render only must be guarded.
Reading the DOM safely
In connectedCallback() the template has not rendered yet, so this.template.querySelector() returns null. In renderedCallback() the elements exist. Use this.template to search the component's own template.
The example below focuses an input once. The hasRendered flag stops the logic from running again on later renders.
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:
<template>
<input type="text" placeholder="Search" />
</template>Two details matter here. The flag is a plain field that the template does not read, so setting it does not cause another render. The if (input) check protects against a template where the element is conditionally absent.
Why unguarded logic goes wrong
renderedCallback() runs once per render, not once per component. Two failures are common.
- Repeated work. Code that attaches a third-party library, adds a listener, or fetches data runs again on every re-render. This duplicates listeners and wastes time.
- Render loops. If the hook changes a value that the template uses, that change schedules another render. The next render calls the hook again, which changes the value again. The loop never ends.
Here is a loop in its smallest form:
import { LightningElement } from 'lwc';
export default class BadCounter extends LightningElement {
count = 0;
renderedCallback() {
// The template displays {count}, so this triggers another render.
this.count += 1;
}
}Each render increments count. The change to count triggers a render, and the cycle repeats.
Guarding patterns
Pick the guard that matches the task.
| Task | Guard |
|---|---|
| Run something once, after the first render | A boolean flag such as `hasRendered` |
| Update the DOM only when data changed | Compare the new value with the last one you stored |
| Work that needs an element that appears later | Check that `querySelector` found the element before acting |
A value-comparison guard looks like this:
import { LightningElement, api } from 'lwc';
export default class ScrollList extends LightningElement {
@api selectedId;
lastScrolledId;
renderedCallback() {
if (this.selectedId === this.lastScrolledId) {
return;
}
this.lastScrolledId = this.selectedId;
const row = this.template.querySelector(
`[data-id="${this.selectedId}"]`
);
if (row) {
row.scrollIntoView();
}
}
}The hook scrolls only when selectedId differs from the last value it handled. lastScrolledId is not used in the template, so assigning it does not cause a render.
Parent and child timing
A parent's renderedCallback() runs after its children have rendered. This means a parent can inspect child elements in its own template. The order across a whole tree is covered in the chapter on parent and child hook order.
Other practices
- Keep the hook short. It runs often, and slow work delays every render.
- Prefer template expressions and reactive properties for changing what the user sees. Use DOM access only when the template cannot express the task, such as focus, scrolling, or measuring size.
- Do not use
document.querySelectorto reach into the component. Usethis.template.querySelectorso you stay inside the component's boundary.
Exercise
A component's template displays {status}. Its renderedCallback() sets this.status = 'ready' every time it runs. Does this cause an infinite loop? Explain, and say how you would fix it if the value were set to a different string each time.
Show answer
No loop occurs if the value is always 'ready'. After the first pass the value does not change, so no new render is scheduled and the hook does not run again. If the hook set a different string each time, each assignment would be a change, which would schedule a render, which would call the hook again, and so on forever. Fix it by moving the assignment out of renderedCallback() (for example to connectedCallback()), or by guarding it with a flag or a comparison so it happens only once.
Exercise
You need to focus an input after the component first appears, but your code in connectedCallback() fails with "Cannot read properties of null". Why, and where should the code go?
Show answer
In connectedCallback() the template has not rendered, so this.template.querySelector('input') returns null. Move the code to renderedCallback() and guard it with a flag so the focus happens only after the first render.