Lifecycle Hooks in Lightning Web Component

Lifecycle Hooks in Lightning Web Component can be considered as a callback method that is triggered at a particular phase of a component instance’s lifecycle.

What are Lifecycle Hooks in Lightning Web Component?

Lifecycle hooks are used to handle the lifecycle of components. Here is list of all method:

  1. Constructor: The constructor() fires when a component instance is created.
  2. ConnectedCallback: Fires when a component is inserted into the DOM.
  3. Render
  4. RenderedCallback: Fires when a component is rendered on the DOM.
  5. DisconnectedCallback: Fires when a component is removed from the DOM.
  6. ErrorCallback: Fires in case of any error during a lifecycle hook or event

A set of pre-defined functions are available and invoked as mentioned below: for more details check the Salesforce website.

1. Constructor()

Invoked when the instance of the component is created, this is similar to the init() method in the aura component. This hook is fired in the parent component first since it flows from parent to child

  • Child elements can’t be accessed because they don’t exist yet
  • Element properties are assigned to the component after construction, so do not access them as they are not yet in existence (public properties decorated with @api)
  • It is necessary to invoke super() from the constructor, since the Lightning web component extends LightningElement which has a constructor and is not supposed to bypass the parent class constructor (To assign the correct property (prototype) and set a value to ‘this’ attribute)

Example of Constructor() method

Example of Constructor() method

output

Example of Constructor() method output

2. ConnectedCallback()

ConnectedCallback() Invoked when the component is inserted into DOM.

  • Child elements can’t be accessed because they don’t exist yet
  • This hook flows from parent component to child component
  • Eventually this method is invoked, all the public properties (decorated with @api) would have been received from the parent component by which we can call an apex method which requires these public properties as input parameters.
  • In order to verify if a component is connected to DOM, the isConnected property can be used
  • Parent elements can be accessed and modified in this lifecycle hook

Example of ConnectedCallback() method

Lifecycle Hooks in Lightning Web Component

output

Example of ConnectedCallback() method output

3. Render()

Render() Invoked after the execution of connectedCallback() method. This hook is used to override the standard rendering functionality in Lightning web components & to update the UI.

  • Flows from parent component to child component
  • Rendering process can be controlled by conditionally rendering the template on the basis of certain conditions or criteria
  • This hook is not technically a lifecycle hook. It is protected method on the LightningElement class

Example of Render() method

output

4. RenderedCallback()

RenderedCallback() Invoked when a component is completely rendered on UI.

  • Flows from child component to parent component
  • This hook should be used cautiously so that an infinite rendering loop is not triggered since this hook is called after the component gets rendered every time
  • Make sure to use a private boolean property like isRendered to track whether renderedCallback() has been executed
  • Not recommended to use renderedCallback() to change the state of the component instead use getter and setter
  • Reactive property in renderedCallback() leads to infinite loop

Example of RenderedCallback() method

Example of RenderedCallback() method

5. DisconnectedCallback()

DisconnectedCallback() Invoked when a component is removed from DOM. Flows from parent component to child component

6. ErrorCallback(error, stack)

ErrorCallback() Invoked when the component throws error in one of the lifecycle hooks (instantiating the component, connecting or rendering)

  • Similar to JavaScript catch{} block, error and stack are the two arguments.error is javascript native error object whereas stack is a string
  • To capture the stack information and render a different template when error is occurred

Here is complete code for your testing

sampleHelloWorld.html

<template>
    <template if:true={error}>
        <lightning-card title="Error Occurred">
            <div>Error Occurred</div>
        </lightning-card>
    </template>
    <template if:false={error}>
        <lightning-card title="Error not Occurred">
        <div>Error did not occur</div>
    </lightning-card>
    </template>
</template>

sampleHelloWorld.js

import { LightningElement, track } from 'lwc'
import templatePrimary from './sampleFirstTemplate.html';
import templateSecondary from './sampleSecondTemplate.html';
 
export default class SampleHelloWorld extends LightningElement{
 
    showTemplatePrimary = true;
 
    @track _isRendered = true;//boolean to check if component is rendered
 
    error;
    stack;
 
    constructor()
    {
        super();//Calling Constructor of LightningElement
        console.log('Constructor called =>');
    }
   
    connectedCallback()
    {
        let varElement = this.template;
        console.log('ConnectedCallback called =>'+varElement.isConnected);
    }
 
    render()
    {
        console.log('Render called =>'+this.showTemplatePrimary);
        return this.showTemplatePrimary ? templatePrimary : templateSecondary;
    }
 
    renderedCallback()
    {
        if(this._isRendered)
        {
            console.log('Parent Component renderedCallback =>');
            this._isRendered = false;
        }
    }
 
    disconnectedCallback()
    {
        console.log('Disconnected Callback =>');
    }
 
    errorCallback(error, stack){
        console.log('Error callBack called =>');
        this.error = error;
        this.stack = stack;
    }
}

sampleFirstTemplate.html

<!-- firstTemplate.html -->
<template>
    <lightning-card>
        <div>
            Primary Template Rendered
        </div>
    </lightning-card>
 
    <c-child-component-test></c-child-component-test>
 
</template>

sampleSecondTemplate.html

<!-- secondTemplate.html -->
<template>
    <lightning-card title="Template Two">
        <div>
            Secondary Template rendered
        </div>
    </lightning-card>
</template>

sampleHelloWorld.js-meta.xml

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>55.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
    <target>lightning__AppPage</target>
    <target>lightning__RecordPage</target>
    <target>lightning__HomePage</target>
  </targets>  
</LightningComponentBundle>

childComponentTest.html

<template>
    <lightning-card title="Child Component">
        <div>
            Child Component Rendered
        </div>
    </lightning-card>
</template>

childComponentTest.js

import { LightningElement, track } from 'lwc';
 
export default class ChildComponentTest extends LightningElement {  
 
    constructor(){
        super(); //Calling Constructor of LightningElement
        console.log('Constructor called =>');
    }
 
    connectedCallback() {}
 
    renderedCallback(){        
        console.log('Child Component renderedCallback from Parent Component =>');
    }
   
}

childComponentTest.js-meta.xml

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>55.0</apiVersion>
    <isExposed>false</isExposed>
</LightningComponentBundle>

Component Lifecycle & Composition Demo

YouTube video

Ravi Teja
Ravi Teja

Salesforce Consultant at Global Consulting Firm
12x Salesforce Certified Application Architect

Articles: 9

7 Comments

  1. Thank you for your Article. Here it is mentioned that the ConnectedCallback() Invoked when the component is inserted into DOM, but Salesforce content says ConnectedCallback() Invoked when the element is inserted into DOM. Which one is correct? Please clarify.

Leave a Reply

Your email address will not be published. Required fields are marked *