SalesforceBlue

Feel the rhythm of Salesforce

LWC

LWC Lifecycle And Wire Services

You must be aware of the LWC Lifecycle Hooks, where we saw the flow of the component lifecycle from creation through the render. However, if you wonder where the wire services fit in this whole lifecycle then feel free to scroll below 🙂

Let’s try to visualize this by creating one component named as lwcLifeCycle and adding the following code to it:

<template>
    <lightning-card>
        Check console logs to visualize the lifecycle callback getting inovoked
    </lightning-card>
 </template>
import { LightningElement, wire} from 'lwc';
import {getObjectInfo} from 'lightning/uiObjectInfoApi';
import ACCOUNT_OBJECT from '@salesforce/schema/Account';


export default class LwcLifeCycle extends LightningElement {
    objectInfoData;
    counter = 1;

    @wire(getObjectInfo, {objectApiName: ACCOUNT_OBJECT})
    objectInfo({error, data}) {

        console.log(this.counter++ + ' - wire service returned with {data= '+data+' & error = '+error+'}');

        if(data) {
            this.objectInfoData = data;
        } 
    }

    constructor() {
        super();
        console.log(this.counter++ +' - constructor invoked');
    }

    connectedCallback() {
        console.log(this.counter++ +' - connectedCallback invoked');
    }

    renderedCallback() {
        console.log(this.counter++ +' - renderedCallback invoked');
    }
}
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>50.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__AppPage</target>
    </targets>    
</LightningComponentBundle>

Now add this component to a lightning app page and view it. Notice the browser console logs to see the results yourself about where the wire services stand in the component lifecycle.

You will be getting an output like the below:


To Summarize our component having a wire service followed the below lifecycle:

  1. constructor invoked
  2. wire service returned for the first time with data = undefined and error = undefined
  3. connectedCallback invoked
  4. renderedCallback invoked
  5. wire services returned again and this time with provisioned data

Thank you for visiting SalesforceBlue.com
If you have any queries feel free to write down a comment below 🙂


2 thoughts on “LWC Lifecycle And Wire Services

  • What is the execution lifecycle if a LWC is wrapped in Aura?

    Reply
    • Pankaj Agrahari

      Hello,

      An lwc wrapped inside an Aura will still follow its own lifecycle.

      You can even see the output by adding this same lwc component given in this post by adding it to an aura component.

      Thanks!

      Reply

Leave a Reply

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