Sub topic 3
connectedCallback(): running code when the component is inserted
connectedCallback() runs when the browser inserts a component into the DOM. It is the standard place to start work that depends on the component's inputs or its environment. This chapter assumes you can write a Lightning Web Component (LWC) with an HTML template and a JavaScript class, and that you know public properties (@api), template expressions, and basic DOM events. It also assumes you have seen constructor() in the previous chapter.
Where it sits in the lifecycle
The hook runs after the constructor and before the first render. The component exists and its public properties are set, but its template has not been built yet.
Three facts follow from this position:
- Public properties that the parent set in its template are already available.
- The component's own template DOM does not exist yet.
- Changes you make to fields now are included in the first render. They do not trigger a second one.
What you can and cannot do
| Task | In connectedCallback? | Notes |
|---|---|---|
| Read `@api` properties set by the parent | Yes | Values set in the parent's template are already assigned. |
| Set or initialize fields | Yes | Included in the first render, so no extra render happens. |
| Add listeners on `window`, `document`, or the host element | Yes | Remove them in `disconnectedCallback()`. |
| Start timers or subscriptions | Yes | Stop them in `disconnectedCallback()`. |
| Call a server method or fetch data | Yes | The call is asynchronous, and the render does not wait for it. |
| Query elements in the component's own template | No | `this.template.querySelector()` returns `null`. |
| Access child components | No | Children are created during render. |
| Rely on wired data being present | No | Wire adapters provide data after the component is connected. |
A first example: a window listener
The hook gives you a point where the component is attached to the page. It is therefore the right place to listen to events on objects outside your template. Events from inside your template are better handled with onclick={handler} in the HTML.
import { LightningElement } from 'lwc';
export default class WindowSize extends LightningElement {
width;
handleResize = () => {
this.width = window.innerWidth;
};
connectedCallback() {
this.width = window.innerWidth;
window.addEventListener('resize', this.handleResize);
}
disconnectedCallback() {
window.removeEventListener('resize', this.handleResize);
}
}A minimal template to display the value:
<template>
<p>Window width: {width}px</p>
</template>The handler is a class field holding an arrow function, so this refers to the component. It also keeps a single stable function reference. removeEventListener only works if you pass the same function you gave to addEventListener. Writing window.addEventListener('resize', () => {...}) inline would leave you with no way to remove the listener.
Setting this.width before the first render costs nothing extra. The template renders once with the correct value.
Reading public properties
Because the parent assigns @api values before connecting the child, you can use them to decide what to initialize.
import { LightningElement, api } from 'lwc';
export default class Countdown extends LightningElement {
@api start = 10;
remaining;
connectedCallback() {
this.remaining = Number(this.start);
}
}This copy happens once. If the parent later changes start, connectedCallback() does not run again, and remaining keeps its old value. To react to later changes, use a getter or a setter on the @api property. Treat connectedCallback() as the place to read the initial state.
Why querySelector returns null
A common first mistake is to touch the template from this hook:
import { LightningElement } from 'lwc';
export default class TooEarly extends LightningElement {
connectedCallback() {
// The template has not been rendered yet.
const input = this.template.querySelector('input');
console.log(input); // null
}
}The element you want does not exist at this point. Move that logic to renderedCallback(), which is covered in a later chapter. If the work can wait, the template can instead react to a field that you set in connectedCallback().
Starting asynchronous work
Loading data is the most common use of this hook. You can mark the method async or chain promises. The framework does not wait for them. The component renders immediately with whatever state it has, then renders again when you assign new values.
import { LightningElement } from 'lwc';
export default class Quote extends LightningElement {
quote;
error;
isLoading = true;
async connectedCallback() {
try {
this.quote = await this.loadQuote();
} catch (e) {
this.error = e;
} finally {
this.isLoading = false;
}
}
loadQuote() {
return new Promise((resolve) => {
setTimeout(() => resolve('Simple is better than complex.'), 500);
});
}
}Because the first render happens before the promise resolves, the template needs a loading state:
<template>
<template lwc:if={isLoading}>
<p>Loading...</p>
</template>
<template lwc:elseif={error}>
<p>Something went wrong.</p>
</template>
<template lwc:else>
<p>{quote}</p>
</template>
</template>Here loadQuote() stands in for a real call, such as an imperative Apex method or a fetch request. In either case you assign to fields after the promise settles, and each assignment can schedule another render.
Assigning to a field after an await is safe if the component is still connected. If the user navigated away, the component may already have been removed, and the assignment then updates an instance nobody sees. For a long request, check a flag that disconnectedCallback() sets, or cancel the request there.
It can run more than once
The name suggests a one-time event, but connectedCallback() fires every time the same element instance is inserted into the DOM. This happens when code removes the element and appends it again, for example when you move a node with appendChild. It also applies to lwc:dom="manual" containers and to elements created in tests with createElement.
Note that a conditional such as lwc:if does not reuse the instance. When the condition turns false, the component is removed. When it turns true again, the framework creates a new instance, and the constructor runs again.
If a setup step must happen only once per instance, guard it. If it must happen on every insertion, pair it with a cleanup in disconnectedCallback().
import { LightningElement } from 'lwc';
export default class Ticker extends LightningElement {
seconds = 0;
intervalId;
hasLoadedConfig = false;
connectedCallback() {
// Runs on every insertion: pair with disconnectedCallback.
this.intervalId = setInterval(() => {
this.seconds += 1;
}, 1000);
// Runs once per instance, even if the element is reinserted.
if (!this.hasLoadedConfig) {
this.hasLoadedConfig = true;
this.loadConfig();
}
}
disconnectedCallback() {
clearInterval(this.intervalId);
this.intervalId = undefined;
}
loadConfig() {
// Placeholder for a one-time data request.
}
}Without the clearInterval call, each reinsertion would start another interval and the counter would speed up.
Order across parent and child
The parent's connectedCallback() runs before its children are created. The children are created while the parent renders, and each child then gets its own constructor and connectedCallback() call. A parent therefore cannot read a child's state from this hook. The next chapters cover the full parent and child order.
The reverse direction works. A child can read what the parent already set, such as @api values, and it can dispatch an event that the parent's template has a handler for.
Errors in this hook
An exception thrown in connectedCallback() is not caught by the same component. It propagates to an ancestor that defines errorCallback(), which is described in a later chapter. If no ancestor handles it, the framework surfaces the error and the component fails to render. A try/catch around risky code, as in the Quote example, keeps the failure local. This matters most for work you cannot predict, such as parsing external input.
An unhandled promise rejection from an async connectedCallback() is different. The method has already returned a promise, so the error does not reach errorCallback(). Catch it yourself.
Guidelines
- Keep the hook short. Start work in it, and put long logic in named methods.
- Do not touch the component's template. Use
renderedCallback()for that. - Every listener, timer, or subscription you create here needs a matching removal in
disconnectedCallback(). - Use stable function references, such as class-field arrow functions, for anything you will remove later.
- Treat the first execution as initialization, and guard it if the same instance may be reinserted.
- Do not assume an
asynchook delays rendering. Design the template to show a loading state.
Check your understanding
Exercise
A component calls this.template.querySelector('button') in connectedCallback() and gets null, even though the template contains a button. Why, and where should the code go?
Show answer
connectedCallback() runs before the first render, so the template's elements do not exist yet. Move the query to renderedCallback(), which runs after the template is rendered. Guard it with a flag if it should only run once.
Exercise
A component starts setInterval in connectedCallback() but never clears it. Another script removes the element and appends it again. What happens to the timers?
Show answer
connectedCallback() runs again for the same instance, so a second interval starts while the first keeps running. The counters then advance faster, and the old timers keep a reference to the component. Clear the interval in disconnectedCallback() so each insertion starts from a clean state.
Exercise
Inside connectedCallback() you set this.total = 5, and the template shows {total}. Does this cause a second render?
Show answer
No. The first render has not happened yet, so the template renders once with total already set to 5.