# What is the purpose of the connectedCallback lifecycle hook, and when is it typically utilized?

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

Read it on the site: https://www.forcechallenges.com/interview-questions/what-is-the-purpose-of-the-connectedcallback-lifecycle-hook-and-when-is-it-typically-utilized

## Answer

**Basics:** Every LWC has a lifecycle: `constructor` -> `connectedCallback` -> `render` -> `renderedCallback` (after each render), and `disconnectedCallback` when removed. `connectedCallback` is the first hook where the component is attached to a document and public properties set by the parent are available. Use it for one-time setup such as calling imperative Apex, registering listeners on `window`/`document`, subscribing to Lightning Message Service or `empApi`, and reading URL state.

**How it works:** The parent is created and connected first, then its children (flow is parent to child). When the framework attaches the host element it calls `connectedCallback()`; afterwards the template renders and `renderedCallback()` fires. Because the component has not rendered yet, `this.template.querySelector(...)` returns `null` for your own template elements. If the component is removed and re-inserted (for example by `lwc:if` toggling, or being moved in the DOM) the hook runs again, so it can fire many times in one component instance's life.

**Advanced / deep dive:** Do not use `constructor` for work beyond calling `super()` and initializing fields: you cannot read `@api` values or set attributes on the host there. `@wire` provisioning also starts around connection, so you rarely need `connectedCallback` for data that a wire adapter can supply; prefer `@wire` for reads (cacheable, reactive) and imperative calls only for user-triggered or non-cacheable work. Do not make it `async` and forget error handling: an unhandled rejection will not break rendering but silently leaves the UI empty. Always pair registrations made here with removal in `disconnectedCallback`, otherwise re-insertion registers duplicates.

**Code / config example:**
```javascript
import { LightningElement, api } from 'lwc';
import getOpenCases from '@salesforce/apex/CaseController.getOpenCases';

export default class CaseList extends LightningElement {
    @api recordId;
    cases = [];
    error;
    _onResize = () => { /* handle layout change */ };

    connectedCallback() {
        window.addEventListener('resize', this._onResize);
        this.load();
    }
    async load() {
        try {
            this.cases = await getOpenCases({ accountId: this.recordId });
        } catch (e) {
            this.error = e;
        }
    }
    disconnectedCallback() {
        window.removeEventListener('resize', this._onResize);
    }
}
```

**Hidden gotchas & must-remember points:**
- The component's own template is not rendered yet, so child element queries return `null`; use `renderedCallback` (guarded by a flag) for DOM work.
- It can run multiple times per instance; keep it idempotent.
- Do not set attributes or child content on the host element here; it violates the lifecycle contract.
- Parent `connectedCallback` runs before child `connectedCallback`, but children render before the parent's `renderedCallback`.
- On record pages, `recordId` may be set by the framework around connection; use a setter or `$recordId` wire if you see `undefined`.
- Do not mutate reactive state in a way that triggers a re-render loop from `renderedCallback`.

**Best practice:** Keep `connectedCallback` small: register listeners and kick off loads, and let `@wire` and `disconnectedCallback` handle the rest.

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