Sub topic 14
Lifecycle hooks and the custom element callbacks
This chapter assumes you know the custom element callbacks from the earlier chapters (connectedCallback and disconnectedCallback), class fields and reactivity, and the bundle structure of an LWC component. It covers when each LWC lifecycle hook runs, which hooks come from the browser standard, and the mistakes people make in each one.
Where the hooks come from
A custom element is a class that the browser calls at defined moments. The standard defines four callbacks:
constructorconnectedCallbackdisconnectedCallbackattributeChangedCallback, plusadoptedCallbackfor moving between documents
An LWC component is a custom element, so the framework builds on the first three. It does not expose attributeChangedCallback or adoptedCallback. Public properties declared with @api replace attribute observation. LWC then adds hooks of its own, because the standard says nothing about rendering a template.
| Hook | Origin | Runs when |
|---|---|---|
| `constructor()` | Standard | The component instance is created |
| `connectedCallback()` | Standard | The element is inserted into a DOM |
| `render()` | LWC | The framework needs to choose a template |
| `renderedCallback()` | LWC | After every render pass finishes |
| `disconnectedCallback()` | Standard | The element is removed from a DOM |
| `errorCallback(error, stack)` | LWC | A descendant throws during a lifecycle hook |
The order of events
The hooks run parent first on the way down and child first on the way up. Rendering a parent has to create its children before the parent's render is complete.
When the parent's connectedCallback runs, the child does not exist yet. When the child's connectedCallback runs, the child's own template is not rendered yet.
constructor
The constructor must call super() first, with no arguments. The element is not yet attached to a document, so keep the constructor small.
- Do not read attributes or public properties. A parent sets them after construction.
- Do not inspect
this.templatechildren. Nothing is rendered. - Do not add attributes to the host element. The standard forbids it during construction.
Initialize plain fields in the class body instead. Class fields run as part of construction, so count = 0; is usually enough and a constructor is rarely needed.
connectedCallback
This hook runs when the element is inserted into a DOM. It is the right place to start work that outlives a single render: subscribing to a message channel, adding a listener on window, starting a timer, or fetching data.
Two edge cases matter here:
- It can run more than once. If a parent moves the element, the browser disconnects and reconnects it. Your setup code must tolerate that. Pair every setup action with a cleanup action in
disconnectedCallback. - The template has not rendered.
this.template.querySelector('p')returnsnullhere on the first run. UserenderedCallbackfor DOM access.
Changing a field inside connectedCallback is safe. The first render has not happened, so the new value is used for it without a second render.
disconnectedCallback
This hook runs when the element leaves the DOM. Undo what connectedCallback started, or the listener or timer keeps running and holds the component in memory.
// clock.js
import { LightningElement } from 'lwc';
export default class Clock extends LightningElement {
time = new Date().toLocaleTimeString();
intervalId;
connectedCallback() {
this.intervalId = setInterval(() => {
this.time = new Date().toLocaleTimeString();
}, 1000);
}
disconnectedCallback() {
clearInterval(this.intervalId);
}
}<!-- clock.html -->
<template>
<p>{time}</p>
</template>Reassigning time every second re-renders the template. intervalId is also a class field, but the template does not read it, so changing it causes no render.
The same callbacks without LWC
The standard version of the same idea shows what the framework wraps. A plain custom element also gets attributeChangedCallback, which only fires for names listed in observedAttributes.
class StatusBadge extends HTMLElement {
static get observedAttributes() {
return ['state'];
}
constructor() {
super();
this.attachShadow({ mode: 'open' });
}
connectedCallback() {
this.draw();
}
disconnectedCallback() {
console.log('removed');
}
attributeChangedCallback(name, oldValue, newValue) {
if (this.isConnected) this.draw();
}
draw() {
this.shadowRoot.innerHTML = `<span>${this.getAttribute('state') ?? 'unknown'}</span>`;
}
}
customElements.define('status-badge', StatusBadge);In this version you attach the shadow root, redraw by hand, and decide when to do it. LWC does those steps for you. The compiler creates the shadow root, and renderedCallback replaces your own draw bookkeeping.
render
render() is optional. It returns a compiled template, which lets one component choose between several HTML files in the same bundle. Most components never define it, and the framework uses the template named after the component. It runs after connectedCallback and again on each re-render, so keep it free of side effects.
renderedCallback
This hook runs after the template has been rendered and the DOM is updated. It runs after the first render and after every later render, and a child's hook runs before its parent's. It is the first point where this.template.querySelector(...) can find elements you declared in the template.
The main hazard is a render loop. If renderedCallback changes a field that the template uses, that triggers another render, which calls renderedCallback again. Guard one-time work with a flag.
<!-- searchBox.html -->
<template>
<input type="search" placeholder="Search" />
</template>// searchBox.js
import { LightningElement } from 'lwc';
export default class SearchBox extends LightningElement {
focused = false;
renderedCallback() {
if (this.focused) return;
this.focused = true;
this.template.querySelector('input').focus();
}
}focused is not used in the template, so setting it does not cause another render. The flag still protects you if the template later changes.
A related edge case is that this.template.querySelector only searches your own shadow tree. It does not reach into a child component's internals.
errorCallback
errorCallback(error, stack) lets a parent catch an error thrown by a descendant during construction, connectedCallback, render or renderedCallback. It does not catch errors in event handlers or in asynchronous code. Use it to show a fallback instead of a blank page.
// errorBoundary.js
import { LightningElement } from 'lwc';
export default class ErrorBoundary extends LightningElement {
failed = false;
message = '';
errorCallback(error, stack) {
this.failed = true;
this.message = error.message;
console.error(stack);
}
}<!-- errorBoundary.html -->
<template>
<p lwc:if={failed}>Something went wrong: {message}</p>
<slot lwc:else></slot>
</template>Common mistakes
- Reading
this.template.querySelector(...)inconnectedCallbackand gettingnull. - Starting a timer or listener and never clearing it in
disconnectedCallback. - Changing a template-bound field in
renderedCallbackwithout a guard. - Reading a public property in the constructor, where it is still unset.
- Expecting
errorCallbackto catch a failed click handler.
Exercise
A component adds a resize listener on window and calls this.template.querySelector('canvas').getContext('2d') to prepare drawing. Which hook should hold each piece of code, and which hook should remove the listener?
Show answer
Add the resize listener in connectedCallback and remove it in disconnectedCallback. Get the canvas context in renderedCallback, guarded by a flag so it runs once, because the canvas does not exist in the DOM until the first render finishes.
Exercise
Which lifecycle hooks come from the custom element standard, and which does LWC add?
Show answer
The standard supplies constructor, connectedCallback and disconnectedCallback. LWC adds render, renderedCallback and errorCallback. It does not expose attributeChangedCallback, because @api properties handle incoming values.