# How does renderedCallback function, and what precautions should developers take to avoid infinite loops?

**Topic:** LWC · **Difficulty:** Medium · **Tags:** LWC, Lifecycle Hooks, renderedCallback

Read it on the site: https://www.forcechallenges.com/interview-questions/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:**
1. First render: constructor, `connectedCallback`, render, `renderedCallback`.
2. Any time a reactive value read by the template changes, the component re-renders and `renderedCallback` fires again.
3. If `renderedCallback` modifies a reactive field used in the template, that triggers another render, which fires `renderedCallback` again: an infinite loop.
4. 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:**
```javascript
import { LightningElement } from 'lwc';
import { loadScript } from 'lightning/platformResourceLoader';
import CHARTJS from '@salesforce/resourceUrl/chartjs';

export default class ChartHost extends LightningElement {
    initialized = false;

    async renderedCallback() {
        if (this.initialized) return;      // guard: run once
        this.initialized = true;
        try {
            await loadScript(this, CHARTJS);
            const canvas = this.template.querySelector('canvas');
            // build chart on canvas ...
        } catch (e) {
            this.initialized = false;      // allow retry on failure
        }
    }
}
```

**Hidden gotchas & must-remember points:**
- It fires after every render, not just the first.
- Setting a field used by the template without a guard causes an infinite render loop.
- Do not query template DOM in `connectedCallback`; it does not exist yet.
- Child `renderedCallback` runs before the parent's.
- `loadScript` should be called once and guarded; repeated loads waste time and may error.
- If a template branch is conditional, the element may be null.

**Best practice:** Use a boolean guard for one-time work and keep `renderedCallback` free of state changes that affect the template.

---
Source: ForceChallenges · last updated 2026-11-02
