How does renderedCallback function, and what precautions should developers take to avoid infinite loops?
Answer
Basics: The template output is only in the DOM after rendering, so anything that needs actual elements (focus, measuring size, initializing a chart library, reading this.template.querySelector) belongs here, not in connectedCallback.
How it works:
- First render: constructor,
connectedCallback, render,renderedCallback. - Any time a reactive value read by the template changes, the component re-renders and
renderedCallbackfires again. - If
renderedCallbackmodifies a reactive field used in the template, that triggers another render, which firesrenderedCallbackagain: an infinite loop. - Guard with a field such as
hasRendered, or compare before assigning.
Advanced / deep dive: Use the guard for one-time setup like loadScript and chart initialization. For repeating operations, make updates idempotent and compare values first. Changes to non-reactive data (a plain DOM style tweak, or a field not used in the template) do not trigger re-render, so they are safe. When a third-party library needs to attach to DOM, combine lwc:dom="manual" with renderedCallback. Do not do expensive work every render; use requestAnimationFrame or compute only when inputs change. Because children render first, a parent's renderedCallback sees fully rendered children, which suits layout measurements. The framework logs warnings in debug mode when many renders occur. Accessing DOM that depends on lwc:if branches requires checking for null. Wire data arriving later triggers additional renders, so do not assume a single call.
Code / config example: