Run Code When a Component Is Created In LWC!

The constructor() method is called when a component instance is created. 

However, it's important to note that you should not add attributes to the host element during construction. 

Instead, you can add attributes to the host element in any other lifecycle hook.

Here are some important points to remember about the constructor():

1. The constructor() flows from parent to child.

2. The first statement in the constructor() must be super() without any parameters. 

This call is essential as it establishes the correct prototype chain and value for "this". 

Always remember to call super() before making any changes to "this".

3. Avoid using a return statement inside the constructor body, unless it is a simple early-return (return or return this).

4. Do not use the document.write() or document.open() methods.

5. Avoid inspecting the element's attributes and children because they don't exist yet during the construction phase.

6. Do not inspect the element's public properties as they are set after the component is created.

Remember, it is best practice to not add attributes to the host element during construction. 

Instead, add them in a different lifecycle hook.

For example, adding attributes to the host element in the constructor() is considered illegal:

import { LightningElement } from "lwc";
export default class Deprecated extends LightningElement {
  constructor() {
    super();
    this.classList.add("new-class");
  }
}

An acceptable approach would be to add attributes in the connectedCallback() lifecycle hook:

import { LightningElement } from "lwc";
export default class New extends LightningElement {
  connectedCallback() {
    this.classList.add("new-class");
  }
}

I hope this clarifies the concept of running code when a component is created. 

Remember to follow these guidelines for better code structure and maintainability. 

#Salesforce #LWC #LightningWebComponents #SalesforceDeveloper #sfdcsaga

Follow Us

Posted By : Sudeer Kamat Date :

view_module Related

label Labels

Comments 0