Sub topic 1
The Life of a Component: Created, Connected, Rendered, Disconnected
Prerequisites
You should know basic JavaScript classes and ES modules, how to create an LWC, reactive properties, and basic DOM events.
The Component Lifecycle
An LWC moves through several stages:
- Created: JavaScript creates the component instance and runs
constructor(). - Connected: The component is inserted into the DOM, and
connectedCallback()runs. - Rendered: LWC creates the component’s HTML. Later changes can trigger more renders.
- Disconnected: The component is removed from the DOM, and
disconnectedCallback()runs.
Each hook has a different purpose. Use the earliest hook that has the resources you need.
constructor(): Setting Up the Instance
The constructor runs when JavaScript creates the component object. It is useful for setting initial field values and preparing instance state.
The constructor must call super() before using this. At this stage, the component is not connected, so do not query its DOM or depend on child elements.
import { LightningElement } from 'lwc';
export default class Counter extends LightningElement {
items;
constructor() {
super();
this.items = [];
}
}connectedCallback(): Running Code When Inserted
connectedCallback() runs after the component is inserted into the DOM. Use it for setup that depends on connection, such as initializing data, subscribing to a service, or registering a global event listener.
A component can be connected, removed, and connected again. Therefore, this hook can run more than once during an instance’s lifetime.
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);
}
}The matching cleanup belongs in disconnectedCallback(). This prevents a listener from continuing to use a component that is no longer displayed.
Exercise
Which hook should initialize an array, and which hook should register a window event listener?
Show answer
Initialize the array in constructor(), and register the listener in connectedCallback().