Lifecycle, Slots and Styling · Lesson 11 of 25
LWC Lifecycle Hooks Explained
A component is created, inserted into the page, rendered, re-rendered as data changes, and eventually removed. LWC lets you run code at each of those moments with lifecycle hooks – methods with special names on your class. Using the right hook for the job is one of the clearest signs of an experienced LWC developer, and "what's the order of lifecycle hooks?" is a classic interview question.
In this lesson
- The five hooks and when they run – logged live
- Parent and child order
- renderedCallback pitfalls
- Catching child errors with errorCallback
The hooks, in order
<!-- lifecycleChild.html -->
<template>
<p>Child says: {label}</p>
</template>
// lifecycleChild.js
import { LightningElement, api } from 'lwc';
export default class LifecycleChild extends LightningElement {
@api label;
constructor() {
super(); // always call super() first
console.log('child: constructor');
}
connectedCallback() {
console.log('child: connectedCallback');
}
renderedCallback() {
console.log('child: renderedCallback');
}
disconnectedCallback() {
console.log('child: disconnectedCallback');
}
}
<!-- lifecycleParent.html -->
<template>
<template lwc:if={showChild}>
<c-lifecycle-child label={label}></c-lifecycle-child>
</template>
<lightning-button label="Change label" onclick={changeLabel}></lightning-button>
<lightning-button label="Remove child" onclick={removeChild}></lightning-button>
</template>
// lifecycleParent.js
import { LightningElement } from 'lwc';
export default class LifecycleParent extends LightningElement {
showChild = true;
label = 'hello';
constructor() {
super();
console.log('parent: constructor');
}
connectedCallback() {
console.log('parent: connectedCallback');
}
renderedCallback() {
console.log('parent: renderedCallback');
}
changeLabel() {
this.label = 'updated';
}
removeChild() {
this.showChild = false;
}
}
Child says: hello [Change label] [Remove child] console: parent: constructor console: parent: connectedCallback console: child: constructor console: child: connectedCallback console: child: renderedCallback console: parent: renderedCallback › click “Change label” Child says: updated [Change label] [Remove child] console: child: renderedCallback console: parent: renderedCallback › click “Remove child” [Change label] [Remove child] console: child: disconnectedCallback console: parent: renderedCallback
What the log shows
- Parent is created and connectedconstructor → connectedCallback, then the parent's template starts rendering
- Child goes through its own cycleconstructor → connectedCallback → renderedCallback
- Parent finishes lastits renderedCallback runs only after all children have rendered
- Updates and removala changed property re-renders the child (renderedCallback again); removing it runs disconnectedCallback
What each hook is for
| Hook | Runs | Use it for | Avoid |
|---|---|---|---|
constructor() | when the instance is created | initialising simple fields (call super() first) | reading @api values or touching the DOM – not set yet |
connectedCallback() | when inserted into the DOM | loading data imperatively, subscribing (LMS, events, timers), reading @api values | accessing child elements – not rendered yet |
renderedCallback() | after every render | DOM work: focusing an element, measuring, third-party libraries | setting fields unconditionally (infinite render loop) |
disconnectedCallback() | when removed from the DOM | cleanup: unsubscribe, clear timers, remove listeners | — |
errorCallback(error, stack) | when a child component throws in a lifecycle hook or render | showing a fallback, logging | handling the component's own errors (only children) |
renderedCallback pitfalls
renderedCallback runs after every render, so one-time setup needs a guard, and changing a reactive field inside it causes another render:
import { LightningElement } from 'lwc';
import { loadScript } from 'lightning/platformResourceLoader';
import CHART_JS from '@salesforce/resourceUrl/chartjs';
export default class SalesChart extends LightningElement {
chartInitialized = false;
renderedCallback() {
if (this.chartInitialized) return; // guard: run the setup once
this.chartInitialized = true;
loadScript(this, CHART_JS).then(() => this.drawChart());
}
// ✗ never: renderedCallback() { this.count++; } – renders forever
}
errorCallback: an error boundary
<!-- riskyWidget.html -->
<template>
<p>Widget loaded</p>
</template>
// riskyWidget.js
import { LightningElement, api } from 'lwc';
export default class RiskyWidget extends LightningElement {
@api config;
connectedCallback() {
if (!this.config) {
throw new Error('riskyWidget needs a config');
}
}
}
<!-- safeContainer.html -->
<template>
<template lwc:if={errorMessage}>
<p class="slds-text-color_error">Something went wrong: {errorMessage}</p>
</template>
<template lwc:else>
<c-risky-widget></c-risky-widget>
</template>
<p>The rest of the page still works.</p>
</template>
// safeContainer.js
import { LightningElement } from 'lwc';
export default class SafeContainer extends LightningElement {
errorMessage;
errorCallback(error, stack) {
this.errorMessage = error.message; // in a real app, also log it (e.g. to a custom object)
}
}
Something went wrong: riskyWidget needs a config The rest of the page still works.
Without the errorCallback, the error would break the whole region of the page. With it, the parent shows a friendly message and everything else keeps working – the same idea as error boundaries in React.
Practice
Try it yourself
Build a clock that starts a one-second timer in connectedCallback and clears it in disconnectedCallback.
Show solution
<!-- liveClock.html --> <template> <p>Ticks: {ticks}</p> </template>// liveClock.js import { LightningElement } from 'lwc'; export default class LiveClock extends LightningElement { ticks = 0; timerId; connectedCallback() { // eslint-disable-next-line @lwc/lwc/no-async-operation this.timerId = setInterval(() => { this.ticks++; }, 100); } disconnectedCallback() { clearInterval(this.timerId); // no timer keeps running after removal console.log('timer cleared'); } }Ticks: 0 › wait 350ms Ticks: 3 › component removed from the page console: timer cleared
The demo ticks every 100 ms so it runs quickly; use 1000 for a real clock. The ESLint comment acknowledges that timers in LWC are deliberate.
Quick check
Which hook runs first in a parent: its renderedCallback or the child's?
The child's. The parent's renderedCallback runs after all children have rendered.
Where should you load data imperatively and subscribe to messages?
connectedCallback.
Does errorCallback catch errors in its own component?
No – only errors from descendant components.
Summary
- Order: constructor → connectedCallback → render → children → renderedCallback; disconnectedCallback on removal.
- connectedCallback for setup and subscriptions; renderedCallback for DOM work, with guards; disconnectedCallback for cleanup.
- errorCallback lets a parent catch child errors and show a fallback.
Finished this lesson?
Mark it complete to track your progress, then carry on with the next lesson.