Life Cycle Hooks – Constructor() in LWC : jayakrishnasfdc

Life Cycle Hooks – Constructor() in LWC
by: jayakrishnasfdc
blow post content copied from  Jayakrishna Ganjikunta
click here to view original post


The constructor() method fires when a component instance is created. Don’t add attributes to the host element during construction. You can add attributes to the host element in any other lifecycle hook.

The constructor flows from parent to child.

These requirements from the HTML: Custom elements spec apply to the constructor().

  • The first statement must be super() with no parameters. This call establishes the correct prototype chain and value for this. Always call super() before touching this.
  • Don’t use a return statement inside the constructor body, unless it is a simple early-return (return or return this).
  • Don’t use the document.write() or document.open() methods.
  • Don’t inspect the element’s attributes and children, because they don’t exist yet.
  • Don’t inspect the element’s public properties, because they’re set after the component is created.

Don’t Add Attributes to Host Element During Construction

You can add attributes to the host element during any stage of the component lifecycle other than construction.
This example is illegal, because it adds an attribute to the host element in the constructor().

constructorExp.html

<template>
    <div>Lifecycle hooks – Constructor in LWC</div>
</template>

constructorExp.js

import { LightningElement } from 'lwc';
export default class ConstructorExp extends LightningElement {
    constructor() {
        super();
        this.classList.add('new-class');
        console.log('In Constructor');
    }
}

Output:


December 06, 2020 at 12:44PM
Click here for more details...

=============================
The original post is available in Jayakrishna Ganjikunta by jayakrishnasfdc
this post has been published as it is through automation. Automation script brings all the top bloggers post under a single umbrella.
The purpose of this blog, Follow the top Salesforce bloggers and collect all blogs in a single place through automation.
============================

Salesforce