Sub topic 3
connectedCallback(): running code when the component is inserted
This chapter assumes you can write a Lightning Web Component with an HTML template and a JavaScript class. It also assumes you know reactive fields, template expressions, and basic DOM events. You should already have seen constructor() in the previous chapter.
What connectedCallback() is for
connectedCallback() is a lifecycle hook. The framework calls it when the component is inserted into the DOM. At that point the component has an owner and a place in the page, but it has not rendered yet.
Use it for work that needs the component to be attached to the page:
- Reading public properties that a parent has set.
- Fetching data or calling an Apex method.
- Subscribing to events on
window,document, or a message channel. - Starting timers.
The constructor runs earlier, before the component is attached. Use the constructor only to set up fields. Move anything that depends on the surrounding page into connectedCallback().
What you can and cannot do
Inside connectedCallback(), the component's template has not been rendered. This leads to one rule you will use often.
this.template.querySelector()finds nothing for elements in your own template, because they do not exist yet.- Public properties set by the parent in its template are available. The parent sets them before it inserts the child.
- You can change reactive fields. The change is picked up by the first render, so it does not cause an extra render.
If you need an element from your own template, wait for renderedCallback(). That hook gets its own chapter.
Example: listening to window resize
The next component stores the window width. It registers a listener when it is inserted.
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);
}
}Three details matter here:
handleResizeis a class field that holds an arrow function. The arrow function keepsthisbound to the component. It is also a single stable function reference.connectedCallback()sets the initial width, then adds the listener.disconnectedCallback()removes the same function reference. If you passed a new function toremoveEventListener, nothing would be removed. This hook is covered in a later chapter, but you should never register a listener without planning its removal.
It can run more than once
connectedCallback() runs each time the component is inserted into the DOM. If a parent removes the component and later inserts it again, the hook runs again. This happens, for example, when an if:true or lwc:if block hides and shows the child.
The constructor, in contrast, runs once per instance. An instance that is moved or reinserted keeps its field values, so connectedCallback() must be safe to run repeatedly. Avoid code that assumes a clean start.
import { LightningElement } from 'lwc';
export default class Ticker extends LightningElement {
seconds = 0;
intervalId;
connectedCallback() {
this.seconds = 0;
this.intervalId = setInterval(() => {
this.seconds += 1;
}, 1000);
}
disconnectedCallback() {
clearInterval(this.intervalId);
}
}Resetting seconds at the start makes the hook safe to repeat. Without it, a reinserted component would continue from its old count.
Common errors
| Mistake | What happens | Fix |
|---|---|---|
| Calling `this.template.querySelector('input')` in `connectedCallback()` | Returns `null` because nothing has rendered | Move the DOM access to `renderedCallback()` |
| Adding a listener with no matching removal | The listener stays active after the component is gone | Remove it in `disconnectedCallback()` |
| Passing a new arrow function to `removeEventListener` | The original listener is not removed | Store one function reference and use it for both calls |
| Assuming the hook runs once | Timers or listeners are registered twice after reinsertion | Reset state and pair every setup with a cleanup |
| Reading child elements | Children do not exist yet | Wait for `renderedCallback()` |
Choosing between constructor and connectedCallback
| Task | Hook |
|---|---|
| Initialize a field to an empty array | `constructor()` or a field initializer |
| Read a value passed in by the parent | `connectedCallback()` |
| Add a `window` listener | `connectedCallback()` |
| Start an interval | `connectedCallback()` |
| Focus an input in your template | `renderedCallback()` |
Exercise
A component calls this.template.querySelector('.title') in connectedCallback() and gets null, even though the template contains an element with the class title. Why does this happen, and where should the lookup move?
Show answer
In connectedCallback() the component has been inserted but has not rendered yet, so the elements in its own template do not exist. Move the lookup to renderedCallback(), which runs after the template has been rendered.
Exercise
A parent shows and hides a child with lwc:if. The child starts a setInterval in connectedCallback() and has no disconnectedCallback(). What happens after the parent hides and shows the child three times?
Show answer
The hook runs on each insertion, so the child starts a new interval every time. Nothing stops the earlier ones, so up to four intervals run at once. Store the interval ID and call clearInterval in disconnectedCallback().