SalesforceLWC Lifecycle Hooks: From Creation to Destruction

SalesforceLWC Lifecycle Hooks: From Creation to Destruction

In Salesforce Lightning Web Components (LWC), there are several lifecycle hooks that allow you to control and manage the component's behavior at different stages of its lifecycle. Here are the key lifecycle hooks in LWC.

Here we are going to display different user interfaces based on certain conditions. And we will see all methods of lifecycle.

Create a new LWC component in VS Code, and name it "multipleTemplateComponent". This will generate an HTML file, a JS file, and a metafile. Next, create a new file with the .html extension and name it "multipleTemplateComponentSecond". The structure of the component should look like the image provided below.

And now please replace the code in each file.

multipleTemplateComponent.html

<template>
    <lightning-card>
        <div class="slds-p-around_medium slds-text-align_center">
           
            <div class="slds-p-around_xx-large slds-text-heading_large" style="color: #0176D3;font-weight:bold">
                Multiple HTML Templates In LWC
            </div>

            <div class="slds-p-around_small slds-text-title_bold">
                First Template
            </div>
            <div class="slds-p-around_small slds-text-title_bold">
                This is First Template, click button to see Second template.
            </div>
            <div class="slds-p-around_small">
                <lightning-button
                        onclick={handleChangeTemplate} 
                        variant="brand"
                        label="Go To Second Template">
                </lightning-button>
            </div>
        </div>
    </lightning-card>
</template>        


multipleTemplateComponentSecond.html

<template>
    <lightning-card>
        <div class="slds-p-around_medium slds-text-align_center">
           
            <div class="slds-p-around_xx-large slds-text-heading_large" style="color: #0176D3;font-weight:bold">
                Multiple HTML Templates In LWC
            </div>

            <div class="slds-p-around_small slds-text-title_bold">
                Second Template
            </div>
            <div class="slds-p-around_small slds-text-title_bold">
                This is Second Template, click button to see First template.
            </div>
            <div class="slds-p-around_small">
                <lightning-button   
                        onclick={handleChangeTemplate} 
                        variant="brand"
                        label="Go To First Template">
                </lightning-button>
            </div>
        </div>
    </lightning-card>
</template>        


multipleTemplateComponent.js

import { LightningElement, track } from 'lwc';
import firstTemplate from "./multipleTemplateComponent.html";
import secondTemplate from "./multipleTemplateComponentSecond.html";
export default class MultipleTemplateComponent extends LightningElement {
   
    @track tempalteName='firstTemplate';

    
    constructor(){
        super(); // we must call super before calling anything  in the constructor
        console.log('in constructor');
    }

    //connected call back
    connectedCallback(){
        console.log('in connected callback');
    }

    //method  for switching between templates
    handleChangeTemplate(){
        if(this.tempalteName === 'firstTemplate'){
            this.tempalteName ='secondTemplate';
        }
        else{
            this.tempalteName ='firstTemplate';
        }
    }

    
    render(){
        console.log('in render');
        return (this.tempalteName === 'firstTemplate') ? firstTemplate : secondTemplate;
    }

    renderedCallback(){
        console.log('in render callback');
    }

    disconnectedCallback(){
        console.log('in disconnected callback');
    }
}        

Add these targets in the metafile, you can add whatever target you want.

  <targets>
        <target>lightning__AppPage</target>
        <target>lightning__RecordPage</target>
        <target>lightning__HomePage</target>
      </targets>        
Here you can see we are rendering two HTML conditionally on a button click. All these are happening with the help of the render method.

I have added all methods of LWC Lifecycle HOOKs to give it a better understanding of the sequence of Lifecycle method calling.

  1. Constructor: This function will be the initial one to be activated, and it is triggered when an instance of a component is instantiated.
  2. ConnectedCallback: This event occurs when a component is added to the DOM.
  3. Render: We are using this method to switch the HTML file of our component.
  4. RenderedCallback: Fires when a component is rendered on the DOM.Called after every render of the component.
  5. DisconnectedCallback: This event occurs when a component is removed from the DOM.
  6. ErrorCallback: Fires in case of any error during a lifecycle hook or event.

When you load the above page you will see a console message in sequence, first, you will get a console message from the constructor, then from connectedCallback, then from render, and then from the renderCallback. See image.

Upon toggling to a different tab and returning to this LWC tab, you’ll notice that the disconnectedCallback console message appears first, followed by the original sequence. This phenomenon occurs because when you transition from this component to others, it becomes detached from the DOM. Upon your return, the entire lifecycle of the component initiates once more. See image.

This is the final result you will get from the above component.


I have provided you with a simple explanation of Multiple HTML Templates and Lifecycle Hooks of LWC.

I hope you found it helpful and informative. Thank you for taking the time to read it. Please let me know your thoughts in the comment section.

#TechWrapIndia #LinkedInNewsIndia #salesforcedeveloper #lwc

#sfdc #crm #crmplateform #crmsoftware #srmsolution #salesforce #salesforce software #salesforceplatform #salesforcemarketing #salesforcedevelopers

要查看或添加评论,请登录

Amir Suhail的更多文章

  • Bed vs. Desk: The Impact on Remote Work Productivity

    Bed vs. Desk: The Impact on Remote Work Productivity

    It's crucial to understand the significance of a dedicated workspace at home. Many people working from home tend to…

  • Dynamic LWC Component Using Design Attributes

    Dynamic LWC Component Using Design Attributes

    Here, we’ll explore the process of generating dynamic LWCs using design attributes. These design attributes allow us to…

    2 条评论
  • Earn Big with Salesforce: Simple Steps to Become a Developer and Get a Well-Paid Job

    Earn Big with Salesforce: Simple Steps to Become a Developer and Get a Well-Paid Job

    Hello everyone, today I want to share my experience as a Salesforce developer and help those who aspire to become one…

  • Salesforce Einstein for Developers

    Salesforce Einstein for Developers

    Salesforce has finally released the long-awaited feature, Salesforce Einstein, for developers. It is now available in…

  • Sharing Rules In Salesforce

    Sharing Rules In Salesforce

    The sharing rules open record access to the users when org-wide sharing settings have been set to anything more…

  • LWC: Spread Operator

    LWC: Spread Operator

    The latest Salesforce Summer '23 release introduced a new feature for LWC components, known as "spread operator". This…

  • The Rise of Tier 2 and Tier 3 Cities in India as Tech and Startup Hubs

    The Rise of Tier 2 and Tier 3 Cities in India as Tech and Startup Hubs

    In recent years, something remarkable has been happening in India. Tier 2 and Tier 3 cities across the country are…

  • Einstein GPT for Salesforce Developers, a threat to developers?

    Einstein GPT for Salesforce Developers, a threat to developers?

    It is crucial that we prioritize upskilling ourselves, especially since AI tools are becoming increasingly accessible…

    4 条评论
  • Dear Freshers

    Dear Freshers

    We all know about the difficulties of getting a job as a fresher, there are many and probably you are facing them now…

    7 条评论

社区洞察