Sub topic 11
Common pitfalls and best practices
This chapter collects the mistakes that come up most often with Lightning Web Component (LWC) lifecycle hooks, and the habits that prevent them. It assumes you know JavaScript classes and ES modules, how to build a basic LWC with an HTML template and a JavaScript class, how reactive properties and template expressions work, and how DOM events work. It also assumes you have read the earlier chapters on each hook. Here the focus is on how the hooks fail and how to write code that does not.
Pitfall map
Most lifecycle bugs fall into a few groups. The table lists each group, the hook involved, and the usual fix.
| Pitfall | Hook involved | Typical fix |
|---|---|---|
| Touching the DOM too early | constructor, connectedCallback | Move DOM access to renderedCallback |
| Repeating one-time work | renderedCallback | Guard with a flag |
| Render loops | renderedCallback | Avoid changing reactive state that the template uses, or guard the change |
| Leaked listeners and timers | connectedCallback, disconnectedCallback | Remove everything you added, using the same reference |
| Errors that blank the page | errorCallback | Add a boundary component with a fallback view |
| Assuming a fixed hook count | all | Write hooks so they can run more than once |
Pitfall 1: Doing too much in the constructor
The constructor runs when the component instance is created. At that point the component has no children and is not attached to the DOM. It must call super() first and should only initialize fields.
Typical mistakes:
- Reading or setting attributes on the host element. The element is not ready for that yet.
- Calling
this.template.querySelector(). Nothing has rendered, so the result isnull. - Starting network requests or timers. These belong in
connectedCallback, where you can pair them with cleanup.
import { LightningElement } from 'lwc';
export default class Counter extends LightningElement {
items;
constructor() {
super();
this.items = [];
}
}Class field initializers (items = [];) are usually simpler than a constructor. Write a constructor only when you need explicit setup order.
Pitfall 2: Expecting the DOM in connectedCallback
connectedCallback runs when the component is inserted into the DOM. The component has not rendered yet, so this.template.querySelector('input') returns null here. Use connectedCallback for work that does not need the rendered output:
- Reading public properties passed in by a parent.
- Fetching data.
- Registering listeners on
windowordocument. - Setting initial state.
Also remember that connectedCallback can run more than once for the same instance. If a parent removes a component and inserts it again, the hook fires again. Do not assume it runs a single time. Code that adds a listener here must remove it in disconnectedCallback, so that a second connection does not register a duplicate.
Pitfall 3: Repeating one-time work in renderedCallback
renderedCallback runs after every render, not only the first. A component renders again whenever a reactive value that the template uses changes. If you put one-time logic here without a guard, it runs again on each render.
A flag fixes this:
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 flag is a plain field that the template does not read, so setting it does not trigger another render. The early return makes the intent clear. Note that if the component is disconnected and reconnected, the flag stays true on the same instance. If you need the logic to run again after reconnection, reset the flag in disconnectedCallback.
Pitfall 4: Render loops
A render loop happens when renderedCallback changes state that the template uses. The change schedules another render, which calls renderedCallback again, which changes the state again, and so on.
This version loops:
import { LightningElement } from 'lwc';
export default class BadLoop extends LightningElement {
rows = 0;
renderedCallback() {
// Changes a value the template displays, so it renders again forever.
this.rows = this.rows + 1;
}
}Ways to avoid it:
- Do not change template-visible state in
renderedCallbackunless you must. - If you must, guard the change with a condition that eventually becomes false. For example, only update when the new value differs from the current value.
- Prefer computing derived values in a getter. A getter runs during rendering and needs no extra render pass.
- Move the work earlier. Data that does not depend on the DOM can be set in
connectedCallback.
import { LightningElement } from 'lwc';
export default class Measured extends LightningElement {
height = 0;
renderedCallback() {
const box = this.template.querySelector('.box');
if (!box) {
return;
}
const measured = box.offsetHeight;
// Guard: only update when the value actually changed.
if (measured !== this.height) {
this.height = measured;
}
}
}This is safe only if the measured value settles. If setting height changes the layout so that offsetHeight changes again, the loop continues. When a guard cannot guarantee that the value settles, store the measurement outside of reactive state or restructure the template.
Pitfall 5: Leaking listeners and timers
Anything you attach outside the component's own template stays alive after the component is removed. That includes listeners on window or document, setInterval and setTimeout callbacks, and subscriptions to message channels or other services. The browser keeps the callback, and the callback keeps this, so the component's memory is not freed. The callback can also keep running against a component that is no longer on screen.
Two rules prevent this:
- Every
addinconnectedCallbackhas a matchingremoveindisconnectedCallback. - The
removecall must receive the same function reference as theaddcall.
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 a class field holding an arrow function. This gives one stable reference, and the arrow function keeps this bound to the component.
The most common version of this bug creates a new function each time:
import { LightningElement } from 'lwc';
export default class LeakyResize extends LightningElement {
connectedCallback() {
window.addEventListener('resize', () => this.update());
}
disconnectedCallback() {
// Does nothing: this arrow function is a different object.
window.removeEventListener('resize', () => this.update());
}
update() {
// handle the resize
}
}The two arrow functions look the same but are different objects, so removeEventListener finds nothing to remove.
Timers follow the same pattern. Store the identifier and clear it:
import { LightningElement } from 'lwc';
export default class Poller extends LightningElement {
timerId;
ticks = 0;
connectedCallback() {
this.timerId = setInterval(() => {
this.ticks += 1;
}, 1000);
}
disconnectedCallback() {
clearInterval(this.timerId);
this.timerId = undefined;
}
}Listeners that you attach to elements inside your own template, or with onclick={handler} in the HTML, are released along with the template. You do not need to remove them yourself.
Pitfall 6: Letting a child error break the page
If a child component throws during its constructor, connectedCallback, render, or renderedCallback, the error propagates up. Without a handler, the whole tree can fail to display. A parent can define errorCallback(error, stack) to catch errors from its descendants, store them, and show a fallback view.
import { LightningElement } from 'lwc';
export default class ErrorBoundary extends LightningElement {
error;
stack;
errorCallback(error, stack) {
this.error = error;
this.stack = stack;
}
}Practical advice:
- Treat the boundary as a separate wrapper component whose template shows either the fallback or a slot with the children. This keeps error handling out of business components.
errorCallbackdoes not catch errors thrown in the component's own hooks or in event handlers. It covers errors from child components.- Errors in asynchronous code, such as a rejected promise, are not lifecycle errors. Handle them with
try/catchor.catch()where you start the work. - Log the error and stack so that the failure is visible to developers, not only replaced by a fallback.
Pitfall 7: Choosing templates carelessly in render()
Overriding render() lets a component return one of several imported templates. It is useful when whole layouts differ by state.
import { LightningElement } from 'lwc';
import signedInTemplate from './signedIn.html';
import signedOutTemplate from './signedOut.html';
export default class Greeting extends LightningElement {
isSignedIn = false;
render() {
return this.isSignedIn ? signedInTemplate : signedOutTemplate;
}
}Keep these points in mind:
render()runs on every render, so it must be fast and free of side effects. Do not fetch data or change state inside it.- It must return a template imported from an HTML file in the component's folder.
- If only a small region changes, use
if:trueandif:falseorlwc:ifblocks in one template. Separate templates are better when the layouts differ substantially. - After the template changes,
renderedCallbackruns against the new DOM. Any element reference you cached from the old template is stale. Query again instead of storing references.
Pitfall 8: Misjudging hook order with children
In a parent with children, the constructor and connectedCallback run parent first, then children. Rendering then proceeds through the children, so renderedCallback runs child first, then parent. A parent's renderedCallback can rely on its children being rendered, but a parent's connectedCallback cannot.
For a parent app containing a child item, the sequence is:
appconstructorappconnectedCallbackitemconstructoritemconnectedCallbackitemrenderedCallbackapprenderedCallback
Do not write code that depends on the order of sibling components relative to each other beyond this general parent and child rule. Communicate through public properties and events instead of relying on timing.
Best practices checklist
- Keep the constructor to
super()and field setup. - Put data requests and listener registration in
connectedCallback. - Treat
connectedCallbackanddisconnectedCallbackas hooks that can run more than once. - Use
renderedCallbackonly for work that needs the rendered DOM, and guard it. - Never change template-visible state in
renderedCallbackwithout a condition that ends. - Keep
render()pure and quick. - Pair every listener, timer, and subscription with cleanup using the same reference.
- Wrap risky subtrees with an error boundary and log what it catches.
- Prefer getters, public properties, and events over timing assumptions.
Practice
Exercise
A component adds window.addEventListener('scroll', () => this.track()) in connectedCallback and calls window.removeEventListener('scroll', () => this.track()) in disconnectedCallback. The page slows down after the component is shown and hidden many times. What is wrong, and how do you fix it?
Show answer
The two arrow functions are different objects, so removeEventListener removes nothing and each connection leaves another live listener on window. Store the handler once, for example handleScroll = () => { this.track(); };, then pass this.handleScroll to both addEventListener in connectedCallback and removeEventListener in disconnectedCallback.
Exercise
A renderedCallback sets this.count = this.count + 1, and the template displays count. What happens, and name two ways to avoid the problem.
Show answer
Each render calls renderedCallback, which changes the displayed value and schedules another render, so the component loops. Avoid it by not changing template-visible state in renderedCallback, by guarding the change with a condition that becomes false (for example only update when the new value differs), by computing the value in a getter, or by moving the work to connectedCallback if it does not need the DOM.
Exercise
A parent component named app contains one child named item. In what order do the item and app renderedCallback hooks run, and what does that mean for the parent's connectedCallback?
Show answer
The item renderedCallback runs first, then the app renderedCallback. So the parent's renderedCallback can rely on the child having rendered, but the parent's connectedCallback runs before any child exists, so it must not query for child elements.