Sub topic 11
Common pitfalls and best practices
This chapter assumes you know JavaScript classes and ES modules, can build a Lightning Web Component with an HTML template and a JavaScript class, and understand reactive properties, template expressions, and basic DOM events. It also assumes you have seen each hook on its own: constructor(), connectedCallback(), render(), renderedCallback(), disconnectedCallback(), and errorCallback(). Here you will review the mistakes that cause most lifecycle bugs and a few habits that prevent them.
Pick the hook by the job
Most bugs start with the right code in the wrong hook. Use this table to choose.
| Task | Hook | Reason |
|---|---|---|
| Initialize fields | `constructor()` | The instance exists, but it has no children and is not in the DOM. |
| Add listeners, read inputs, start timers | `connectedCallback()` | The component is inserted into the DOM. |
| Pick one of several templates | `render()` | It returns the template to use. |
| Touch rendered elements | `renderedCallback()` | The template has been rendered. |
| Release listeners and timers | `disconnectedCallback()` | The component is being removed. |
| Show a fallback for child failures | `errorCallback()` | Errors from descendants arrive here. |
Pitfall 1: Unguarded work in renderedCallback
renderedCallback() runs after every render, not only the first one. If it does expensive work, that work repeats. If it changes a reactive field that the template uses, it triggers another render, which calls renderedCallback() again, and so on. This is an infinite render loop.
The following component has this bug:
import { LightningElement } from 'lwc';
export default class Broken extends LightningElement {
count = 0;
renderedCallback() {
// Changes a field used in the template on every render.
this.count = this.count + 1;
}
}Guard one-time work with a flag, as in the focus example from the earlier chapter:
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 not used in the template, so setting it does not cause another render. If you must change a template-bound field in renderedCallback(), do it only when a condition says the value really needs to change.
Pitfall 2: Leaking listeners and timers
Anything you start in connectedCallback() that outlives the component must be stopped in disconnectedCallback(). This covers window and document listeners, setInterval, and setTimeout callbacks that are still pending.
Two details cause most leaks:
removeEventListenerneeds the same function reference you passed toaddEventListener. An inline arrow function cannot be removed, because you have no reference to it.- A component can be disconnected and connected again, for example when a parent moves it. Setup in
connectedCallback()and cleanup indisconnectedCallback()must be symmetric so each connection starts from a clean state.
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 class field handleResize is one stable function, so both calls use the same reference.
Pitfall 3: Doing DOM work too early
In constructor(), the component has no children and is not attached to the DOM. Do not read attributes, query the template, or touch the host element there. Call super() first, then set fields only.
In connectedCallback(), the template has not rendered yet, so this.template.querySelector() finds nothing. Query the template in renderedCallback().
Pitfall 4: Wrong assumptions about parent and child order
The parent's connectedCallback() runs before its children are created. The parent's renderedCallback() runs after all its children have rendered. Do not assume a child exists in the parent's connectedCallback(). Do not assume the parent has finished rendering inside a child's connectedCallback().
Pitfall 5: Ignoring errors from children
An error thrown by a child during its lifecycle can break the whole subtree. A parent that defines errorCallback() receives the error and can switch to a fallback view.
import { LightningElement } from 'lwc';
export default class ErrorBoundary extends LightningElement {
error;
stack;
errorCallback(error, stack) {
this.error = error;
this.stack = stack;
}
}Your template can then use error to render a message instead of the failed child. The hook catches errors from descendants, not from the component that defines it.
Best practices
- Keep
constructor()minimal. Callsuper()first and only initialize fields. - Put setup in
connectedCallback()and write its matching cleanup indisconnectedCallback()at the same time. - Guard
renderedCallback()with a flag or a condition before doing anything. - Store listener functions as class fields so you can remove them.
- Use
render()to choose between whole templates. Useif:trueandif:falseor similar template conditions for small differences. - Place
errorCallback()in a wrapper component around risky children.
Exercise
A component adds window.addEventListener('scroll', () => this.update()) in connectedCallback(). After the component is removed, update() still runs. Why, and how do you fix it?
Show answer
The arrow function passed to addEventListener has no reference you can pass to removeEventListener, so the listener stays on window after removal. Store the handler as a class field, such as handleScroll = () => this.update();. Add it with window.addEventListener('scroll', this.handleScroll) in connectedCallback(). Remove it with window.removeEventListener('scroll', this.handleScroll) in disconnectedCallback().
Exercise
Why does this.template.querySelector('input') return null in connectedCallback() but find the element in renderedCallback()?
Show answer
connectedCallback() runs when the component is inserted, before its template renders, so the input does not exist yet. renderedCallback() runs after the render, when the input is in the DOM.