Sub topic 2
constructor(): setting up the instance
This chapter assumes you can write a Lightning Web Component (LWC) with an HTML template and a JavaScript class. It also assumes you know reactive fields, template expressions, and basic DOM events. Here you will learn what the constructor() hook is for, what is safe to do in it, and what is not.
Where the constructor fits
Every component goes through a lifecycle: it is created, connected to the DOM, rendered, and later disconnected. The constructor runs first. The engine calls it when it creates the component instance, before the component is inserted into the page.
The constructor runs once per instance. If a parent creates three copies of a component, the constructor runs three times, once for each copy.
The basic shape
An LWC class extends LightningElement. If you write a constructor, the first statement must be super(). This call sets up the base class. Without it, JavaScript throws an error as soon as you touch this.
import { LightningElement } from 'lwc';
export default class Counter extends LightningElement {
items;
constructor() {
super();
this.items = [];
}
}Two rules apply to this constructor:
- Call
super()first, with no arguments. - Do not return a value from the constructor.
What is safe to do
At construction time, the component has no children and is not attached to the DOM. The constructor is therefore a good place for plain, in-memory setup:
- Give fields their starting values, such as arrays, objects, and counters.
- Set up internal state that does not depend on the page.
- Bind or create helper objects the class will use later.
In many cases you do not need a constructor at all. A class field initializer does the same job with less code:
import { LightningElement } from 'lwc';
export default class Counter extends LightningElement {
items = [];
}Use a constructor when the initial value needs several steps to compute, or when you want all setup in one visible place.
What is not safe to do
Because the component is not yet in the DOM, many things you might expect to work do not.
| Task | In the constructor? | Why |
|---|---|---|
| Set a field to a default value | Yes | It only changes the instance. |
| Read a public property passed by the parent | No | Properties are assigned after construction, so the value is not available yet. |
| Query child elements with `this.template.querySelector` | No | The template has not rendered, so there are no children. |
| Read or change attributes on the host element | No | The spec forbids it during construction. |
| Add a window or document listener | Avoid | The component may never be connected, and there is no matching cleanup yet. Use `connectedCallback`. |
| Fetch data | Avoid | The inputs from the parent are not set. Use `connectedCallback`. |
The public property row is the most common source of confusion. Suppose a parent writes <c-card record-id="001">. Inside Card, the recordId field is still undefined in the constructor. By the time connectedCallback runs, it holds "001".
import { LightningElement, api } from 'lwc';
export default class Card extends LightningElement {
@api recordId;
constructor() {
super();
console.log(this.recordId); // undefined
}
connectedCallback() {
console.log(this.recordId); // "001"
}
}The same reasoning applies to the host element. The element that wraps your component exists, but you must not read or write its attributes from the constructor. Setting attributes there is a common mistake and the engine reports it as an error.
Constructor or connectedCallback?
Both run early, so choose by what the code needs.
- If the code only sets up the instance and needs nothing from outside, use the constructor or a field initializer.
- If the code reads public properties, registers listeners, or starts requests, use
connectedCallback.
There is also a difference in how often they run. The constructor runs once per instance. connectedCallback runs each time the component is inserted into the DOM, which can happen more than once if the component is removed and added back. Work that must happen on every insertion belongs in connectedCallback. The next chapters cover that hook in detail.
A common error
Forgetting super() is the usual mistake. This code fails:
import { LightningElement } from 'lwc';
export default class Broken extends LightningElement {
constructor() {
this.items = []; // ReferenceError: must call super constructor first
}
}The fix is to add super(); as the first line of the constructor, as in the earlier Counter example.
Exercise
A parent renders <c-order-summary order-id="A-17">. In OrderSummary, you want to call a method using this.orderId as soon as the component starts. Why does reading this.orderId in the constructor not work, and which hook should you use instead?
Show answer
Public properties are assigned by the parent after the instance is constructed, so this.orderId is still undefined in the constructor. Use connectedCallback, where the property already holds "A-17".
Exercise
Rewrite this constructor so it is valid and as short as possible: constructor() { this.names = []; super(); }
Show answer
Remove the constructor and use a field initializer: names = [];. If you keep a constructor, super(); must come first, followed by this.names = [];.