Sub topic 1
The life of a component: created, connected, rendered, disconnected
A Lightning Web Component (LWC) is not a static file that runs once. The framework creates an instance, inserts it into the page, draws it, redraws it when data changes, and eventually removes it. Lifecycle hooks are methods you define on your class. The framework calls them at fixed points in this sequence.
This chapter gives you the overall model. Later chapters cover each hook in detail. Here you will learn what the phases are, which hook belongs to which phase, and how to observe the order yourself.
Prerequisites
This chapter assumes you can do the following:
- Read and write JavaScript classes and ES module imports and exports.
- Create a Lightning web component with an HTML template and a JavaScript class that extends
LightningElement. - Use fields and template expressions such as
{name}to show data. - Attach a basic DOM event handler such as
onclick={handleClick}.
You also need somewhere to run a component and read the browser console. A Salesforce scratch org, a sandbox, or the Lightning Web Components Playground all work.
What a lifecycle hook is
A lifecycle hook is a method with a specific name. If your class defines it, the framework calls it at a particular moment. You never call these methods yourself. If you leave a hook out, the framework skips it.
The hooks covered in this tutorial are:
| Hook | Runs when |
|---|---|
| `constructor()` | The component instance is created |
| `connectedCallback()` | The component is inserted into the DOM |
| `render()` | The framework needs to know which template to use |
| `renderedCallback()` | The component has finished rendering |
| `disconnectedCallback()` | The component is removed from the DOM |
| `errorCallback(error, stack)` | A descendant component throws an error |
The four phases
You can think of a component's life as four phases. Hooks mark the transitions between them.
- Created. The framework builds an instance of your class. The
constructor()runs. - Connected. The component's host element is inserted into a DOM tree.
connectedCallback()runs. - Rendered. The framework evaluates the template and builds the component's DOM.
render()runs first, thenrenderedCallback()runs once the output is in place. - Disconnected. The host element is removed from the DOM.
disconnectedCallback()runs.
Between phases 3 and 4, the component may render many times. Each time its data changes in a way the template depends on, the framework re-renders it and calls renderedCallback() again.
The diagram shows one instance. Disconnected is not always the end, as the next sections explain.
What each phase is for
Each phase gives you different things to work with. Choosing the right hook is mostly a matter of knowing what is available at that moment.
Created: the constructor
When the constructor runs, the component exists but has no place in the page. It has no children and no host attributes you can rely on, and its public properties have not been set by a parent yet.
Use the constructor only to initialize fields. It must call super() first. Do not try to read the DOM here.
import { LightningElement } from 'lwc';
export default class Counter extends LightningElement {
items;
constructor() {
super();
this.items = [];
}
}Connected: the component is in the DOM
By the time connectedCallback() runs, the host element is in a DOM tree. Public properties passed by a parent have been set. The component has not rendered yet, so this.template.querySelector() finds nothing.
This is the usual place for setup that depends on being on the page. Examples are fetching data, subscribing to a message channel, or adding a listener on window or document.
Rendered: the template is on screen
render() decides which template to use. Most components never define it, because the framework uses the HTML file that shares the class's name. After the template is evaluated and its DOM is in place, renderedCallback() runs. This is the first moment you can query the component's own elements.
Disconnected: the component leaves
disconnectedCallback() is your chance to undo what connectedCallback() did. If you added a listener to window, remove it here. If you started a timer, stop it.
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);
}
}The handler is stored in a field so that removeEventListener receives the same function reference that addEventListener received. Passing a new arrow function would remove nothing.
Observe the lifecycle yourself
Reading about the order is less convincing than seeing it. The following example is a component that logs from every hook. It also has a button that changes a field the template uses.
Create a component named lifecycleLogger.
lifecycleLogger.html:
<template>
<p>Clicks: {clicks}</p>
<button onclick={handleClick}>Click me</button>
</template>lifecycleLogger.js:
import { LightningElement } from 'lwc';
import template from './lifecycleLogger.html';
export default class LifecycleLogger extends LightningElement {
clicks = 0;
constructor() {
super();
console.log('1 constructor');
}
connectedCallback() {
console.log('2 connectedCallback');
}
render() {
console.log('3 render');
return template;
}
renderedCallback() {
console.log('4 renderedCallback');
}
disconnectedCallback() {
console.log('5 disconnectedCallback');
}
handleClick() {
this.clicks += 1;
}
}The render() override imports the component's own template and returns it. This is the same as the default behavior, and it lets us log the call.
Now create a parent component named lifecycleHost that can add and remove the logger.
lifecycleHost.html:
<template>
<button onclick={handleToggle}>Toggle logger</button>
<template lwc:if={show}>
<c-lifecycle-logger></c-lifecycle-logger>
</template>
</template>lifecycleHost.js:
import { LightningElement } from 'lwc';
export default class LifecycleHost extends LightningElement {
show = false;
handleToggle() {
this.show = !this.show;
}
}Place lifecycleHost on a page and open the browser console. Then try these steps.
- Click Toggle logger once. The console shows
1 constructor,2 connectedCallback,3 render,4 renderedCallback, in that order. - Click Click me. The console shows
3 renderand4 renderedCallbackagain. The constructor andconnectedCallbackdo not run, because the instance is already created and connected. - Click Toggle logger again. The console shows
5 disconnectedCallback. - Click Toggle logger a third time. You see
1 constructoragain, becauselwc:ifcreated a brand new instance. Theclickscount is back to 0.
Step 4 matters. The conditional directive does not hide the component. It destroys it and later creates a new one, so any state held in the old instance is lost.
One instance, many connections
The constructor runs once per instance. connectedCallback() and disconnectedCallback() can run more than once on the same instance, because an element can be removed from the DOM and then inserted again.
This happens when code moves an existing element. For example, you might create an element with document.createElement and call appendChild on it twice in different places. Each insertion triggers connectedCallback(), and each removal triggers disconnectedCallback().
Write your hooks so they are safe to run in pairs. Whatever connectedCallback() acquires, disconnectedCallback() should release. Then it does not matter how many times the cycle repeats.
What causes the render phase to repeat
The framework re-renders a component when a value the template read during its last render changes. The rule is more specific than "any field changed":
- A field that appears in the template, such as
{clicks}, triggers a re-render when you assign a new value to it. - A field that the template never reads does not trigger a re-render, even if you change it.
- For objects and arrays, reassigning the field is detected. Changing a property inside an object, such as
this.user.name = 'Ada', is only detected if the field is decorated with@trackor the object is replaced.
Each re-render calls render() and then renderedCallback(). It does not call the constructor or connectedCallback(). A later chapter covers re-render triggers in full. For now, remember that renderedCallback() can run many times, so work placed there must be written to tolerate repetition.
import { LightningElement } from 'lwc';
export default class FocusInput extends LightningElement {
hasRendered = false;
renderedCallback() {
if (this.hasRendered) {
return;
}
this.hasRendered = true;
const input = this.template.querySelector('input');
if (input) {
input.focus();
}
}
}The hasRendered flag makes the focus logic run after the first render only. Without it, every re-render would pull focus back to the input. Changing a reactive field inside renderedCallback() without a guard can also cause an endless render loop, which a later chapter covers.
Parents and children
Real pages are trees of components. Hooks fire for each component in the tree, and the order is interleaved. When a parent renders, its template creates the child components. So the parent's constructor and connectedCallback() run first, then each child goes through its own constructor, connectedCallback(), and render. The parent's renderedCallback() runs last, because the parent is only finished once its children are in place.
For one parent with one child, the order is:
- Parent
constructor - Parent
connectedCallback - Parent
render - Child
constructor - Child
connectedCallback - Child
render - Child
renderedCallback - Parent
renderedCallback
Two consequences follow. A child's renderedCallback() runs before its parent's, so a parent can query its children there. And a parent cannot query its children in connectedCallback(), because they do not exist yet. A later chapter walks through this order in more detail.
Choosing a hook: a quick guide
| You want to... | Use |
|---|---|
| Initialize plain fields | `constructor()` (after `super()`) |
| Fetch data, subscribe, or add global listeners | `connectedCallback()` |
| Pick between several templates | `render()` |
| Read or modify the component's own DOM | `renderedCallback()` |
| Remove listeners, stop timers, unsubscribe | `disconnectedCallback()` |
| Handle errors thrown by child components | `errorCallback()` |
Summary
- A component moves through created, connected, rendered, and disconnected phases. Each phase has a hook.
- The constructor runs once per instance.
connectedCallback()runs each time the element is inserted.renderedCallback()runs after every render. - A re-render is triggered by a change to something the template read. It runs
render()andrenderedCallback()but not the constructor orconnectedCallback(). - Removing a component with
lwc:ifdestroys the instance. Showing it again creates a new one and runs the constructor again. - Parent and child hooks interleave. The parent's
renderedCallback()runs after all its children have rendered.
Exercise
A component adds a resize listener on window in connectedCallback(). A parent shows and hides it with lwc:if, and the user toggles it on and off five times. The component has no disconnectedCallback(). What problem does this cause, and how do you fix it?
Show answer
Each time the component is shown, a new instance is created and connectedCallback() adds another listener to window. Without disconnectedCallback(), the listeners from removed instances are never removed, so after five toggles up to five listeners are active. They keep the old instances alive in memory and keep running their handlers. The fix is to store the handler in a field (for example handleResize = () => { ... };) and call window.removeEventListener('resize', this.handleResize) in disconnectedCallback().
Exercise
Using the lifecycleLogger component, list the hooks that appear in the console, in order, when you click "Click me" once after the component is already on the page. Then explain why the constructor is not among them.
Show answer
The console shows 3 render and then 4 renderedCallback. Clicking increments clicks, which the template reads, so the framework re-renders the existing instance. The constructor runs only when an instance is created, and connectedCallback() runs only when the element is inserted into the DOM. Neither event happens on a re-render.
Exercise
A parent component contains one child component. Which renderedCallback() runs first, the parent's or the child's, and why does it matter for code that queries the DOM?
Show answer
The child's renderedCallback() runs first. The parent's finishes last, after its children are rendered. This means the parent can safely query its child elements in renderedCallback(), but not in connectedCallback(), where the children have not been created yet.