Sub topic 2
constructor(): setting up the instance
This chapter covers the first hook that runs for a Lightning Web Component. It assumes you can write a JavaScript class and import modules. It also assumes you have built a component with an HTML template and a JavaScript file, and that you know reactive fields, template expressions, and basic DOM events. The chapter explains what the constructor is for and what you can safely do in it. It also covers the errors you see when you break its rules.
Where the constructor sits in the lifecycle
Every Lightning Web Component is a JavaScript class that extends LightningElement. The framework creates an instance of that class when it needs the component. That creation calls the class constructor. The constructor runs once for each instance, before any other lifecycle hook.
The constructor is the earliest point at which your code runs. The component is not yet attached to the DOM (the browser's live tree of page elements). It has no children, and its parent has not passed it any values.
The order in this diagram explains most of the constructor's rules. Almost everything you might want to read, such as passed-in values, child elements, and attributes, does not exist when the constructor runs.
The basic shape
The constructor is optional. Many components never define one, because class fields (properties declared in the class body) cover most setup needs. When you do define one, it must follow this shape:
import { LightningElement } from 'lwc';
export default class Counter extends LightningElement {
items;
constructor() {
super();
this.items = [];
}
}Three rules apply here.
- Call
super()first, before you touchthis.LightningElementdoes the setup that makes your class a component. A derived class cannot usethisuntil the parent constructor has run. - Take no parameters. The framework creates the instance for you and passes no arguments.
- Do not return a value. A constructor that returns something other than the instance breaks the framework's assumptions.
If you forget super(), or use this before it, JavaScript throws a ReferenceError. The message reads along the lines of "Must call super constructor in derived class before accessing 'this' or returning from derived class constructor". The component then fails to load.
What the constructor is good for
Use the constructor to initialize the instance's own state. It is a good place to do the following:
- Set default values for fields that depend on a computation instead of a literal.
- Create plain objects, arrays,
MaporSetinstances that your methods use later. - Bind or create helper objects that live as long as the component.
- Add event listeners to the host element with
this.addEventListener(...). The host element is the custom element that represents your component. Salesforce's documentation uses the constructor for this.
Here is a complete component that uses a constructor. The JavaScript file is shoppingList.js:
import { LightningElement } from 'lwc';
export default class ShoppingList extends LightningElement {
items;
nextId;
constructor() {
super();
this.items = [];
this.nextId = 1;
}
handleAdd() {
const input = this.template.querySelector('lightning-input');
const label = input.value;
if (!label) {
return;
}
this.items = [...this.items, { id: this.nextId++, label }];
input.value = '';
}
}The template is shoppingList.html:
<template>
<lightning-input label="Item"></lightning-input>
<lightning-button label="Add" onclick={handleAdd}></lightning-button>
<ul>
<template for:each={items} for:item="item">
<li key={item.id}>{item.label}</li>
</template>
</ul>
</template>The constructor sets up items and nextId before the first render. The template can then loop over items without checking for undefined.
Notice that handleAdd reads the input with this.template.querySelector. That is safe in an event handler, because the DOM exists by then. It would not work in the constructor.
Constructor or class field?
You can often skip the constructor. A class field initializer does the same job with less code:
import { LightningElement } from 'lwc';
export default class ShoppingList extends LightningElement {
items = [];
nextId = 1;
}Field initializers run as part of construction. For a class that extends LightningElement, they run right after super() returns, so they behave like the first lines of the constructor. Choose between them like this:
| Situation | Prefer |
|---|---|
| A literal default such as `0`, `''`, `[]`, or `false` | Class field |
| A default that needs several statements or a helper call | Constructor |
| Setting up a host-element listener | Constructor |
| Anything that needs values passed in by the parent | Neither. Use `connectedCallback()` |
The last row matters most, and the next section explains why.
What you must not do in the constructor
The framework creates the instance before it knows anything about its surroundings. This table lists what is unavailable and what to do instead.
| Do not do this in the constructor | Why it fails | Do this instead |
|---|---|---|
| Read `@api` properties that a parent sets | The parent assigns them after construction | Read them in `connectedCallback()` |
| Query the template with `this.template.querySelector(...)` | The component has not rendered, so the result is `null` | Use `renderedCallback()` |
| Inspect the host element's attributes or children | They do not exist yet | Use `connectedCallback()` or later |
| Set attributes on the host element, for example `this.setAttribute(...)` | The framework forbids attributes on the element during construction and can throw | Set them in `connectedCallback()` |
| Fetch data or start timers | Inputs are not ready, and a timer started here may never be cleaned up | Start them in `connectedCallback()` and stop them in `disconnectedCallback()` |
The mistake in the first row is the most common one. Consider this component, which gets a record ID from its parent:
import { LightningElement, api } from 'lwc';
export default class RecordBadge extends LightningElement {
@api recordId;
label;
constructor() {
super();
// Wrong: recordId has not been set yet, so it is undefined here.
this.label = 'Record ' + this.recordId;
}
}The label becomes "Record undefined". The code throws no error, and the bug only shows up in the output. The fix is to move the line to connectedCallback():
import { LightningElement, api } from 'lwc';
export default class RecordBadge extends LightningElement {
@api recordId;
label;
connectedCallback() {
this.label = 'Record ' + this.recordId;
}
}By the time connectedCallback() runs, the parent has assigned recordId. The next chapter covers that hook in detail.
The component has no children yet
A component's children are created while its template renders, and rendering happens after the constructor. A parent's constructor therefore runs before any child component has been created. Inside the constructor, this.template exists, but it holds nothing you can query:
import { LightningElement } from 'lwc';
export default class EmptyAtStart extends LightningElement {
constructor() {
super();
const firstInput = this.template.querySelector('input');
console.log(firstInput); // null: nothing has rendered
}
}The same applies to this.querySelector, which looks at light DOM children that a parent passes into slots. Treat the constructor as running before the component has any DOM at all.
How often the constructor runs
The constructor runs once for each instance, but the number of instances depends on how the component is used.
- A component placed unconditionally in a parent template is constructed once, when the parent first renders.
- A component inside
if:trueorlwc:ifis constructed each time the condition turns true after being false. When the condition turns false, the framework removes that instance. The next time, it creates a new one. - Each item in a
for:eachloop gets its own instance, so a list of ten rows runs the constructor ten times. - If the same element is moved to a different place in the DOM, the constructor does not run again.
disconnectedCallback()andconnectedCallback()run instead.
The last point is why one-time setup of instance state belongs in the constructor, while work that must repeat on every insertion belongs in connectedCallback().
Constructors and the parent-child order
A parent's constructor runs before its children's constructors. The parent's template has to be evaluated before it can know which children to create. So the sequence for a parent containing one child starts with the parent's constructor, then the child's constructor. The remaining hooks, including the later ones, come after both. A later chapter walks through the full interleaving. For now, remember that a parent constructor cannot rely on any child existing.
Common mistakes and how they show up
- Missing
super(). The component fails to load with aReferenceError. Addsuper();as the first statement. - Using
thisbeforesuper(). This gives the same error. Movesuper()to the top. - Reading
@apivalues. You getundefinedand no error. Move the logic toconnectedCallback(). - Querying the template.
querySelectorreturnsnull, and a later.focus()or.valuecall throws aTypeError. Move the logic torenderedCallback(). - Starting a timer or listener on
windowordocument. Nothing in the constructor pairs with cleanup. The listener or timer can leak after the component is removed. Start it inconnectedCallback()and stop it indisconnectedCallback(). - Putting too much in it. Long computations here slow down every instance's creation, which hurts most inside large lists. Keep the constructor light.
A defensible default
A good habit is to leave out the constructor unless you have a reason for it. If a field default is a literal, write it as a class field. If you need host-element listeners or a few lines of setup, add a short constructor with super() first. Put everything that depends on the outside world into connectedCallback().
Exercise
A component declares @api recordId; and has a constructor that calls super() and then runs this.title = 'Account ' + this.recordId;. The parent passes recordId="001xx". What does title contain, and where should the assignment move to?
Show answer
title contains "Account undefined". The parent sets recordId after the constructor finishes, so the constructor reads it too early. Move the assignment to connectedCallback(), where recordId is already set.
Exercise
What happens if a constructor reads this.template.querySelector('input'), and why?
Show answer
It returns null. The constructor runs before the component renders, so its template has no DOM elements yet. Use renderedCallback() for DOM queries that need the rendered output.
Exercise
A list renders ten <c-row> components with for:each. How many times does the c-row constructor run when the list first appears, and how many times does it run if the parent hides and shows the list with lwc:if?
Show answer
Ten times for the first render, because each loop item gets its own instance. Hiding the list removes those instances, and showing it again creates ten new ones, so the constructor runs ten more times, for twenty in total.