Role and Properties of connectedCallback() in LWC Lifecycle with Example

connectedCallback() in LWC Lifecycle
Chinmaya By Chinmaya
7 Min Read

Introduction

The connectedCallback() is the second lifecycle hook in LWC, called after the Constructor, and is triggered when a LWC component is inserted into the DOM.

It is a crucial hook for performing tasks that require the component to be part of the document’s structure.

Here’s a detailed explanation of its role:

Role and Properties of connectedCallback():

1. Executed When the Component is Added to the DOM

The connectedCallback() is automatically triggered, when the component is inserted into the DOM.

				
					connectedCallback() {
    console.log('Component is now in the DOM');
}
				
			

2. Ideal to Set Properties and Initialize Variables:

    • You can define and initialize properties or variables inside the connectedCallback() method.
    • It is often used for preparing data or setting up the initial state of the component.

3. Access to the DOM

    • By the time connectedCallback is called, the component’s DOM structure is available.
    • Unlike constructor, from connectedCallback() you can access and interact with any DOM elements.

4. Manage Message Channels

    • Subscribing to a Lightning Message Channel can be done in connectedCallback() to ensure the component is ready to listen to messages.
    • Corresponding unsubscription should be handled in the disconnectedCallback() method to prevent memory leaks.
    • Note:

      Always unsubscribe from message channels or remove any event listeners added in connectedCallback() when the component is removed from the DOM (disconnectedCallback()).

Example:

				
					connectedCallback() {
    this.subscribeToChannel();
}
				
			

5. Call Apex Methods:

    • You can call Apex methods inside connectedCallback() using @wire or imperative Apex calls (@salesforce/apex imports).

    • However, be cautious of performance issues, as calling Apex synchronously during component initialization might impact the user experience.

    • Note:

      Avoid making expensive operations (like multiple Apex calls) in connectedCallback() because it directly affects the loading performance.

6. Create and Dispatch Custom Events:

    • While you can dispatch custom events in connectedCallback(), it is not a common practice.

    • Custom events are usually dispatched as a response to user actions or component updates, not during initialization.

6. Triggered Each Time the Component is Inserted

    • If a component is removed and re-added to the DOM, the connectedCallback will be triggered again.

7. Call uiRecordApi:

    • uiRecordApi methods (like getRecord) can be invoked in connectedCallback() to fetch or manipulate Salesforce record data.

8. Child elements cannot be accessed

    • You cannot access child LWC elements from Parent LWC Component’s connectedCallback() because they haven’t been rendered yet.
      So, technically when connectedCallback() runs on Parent Component, Child LWC component don’t exist yet.

    • For accessing child elements, use the renderedCallback() method.

When to use connectedCallback?

    1. Use connectedCallback() when you need to perform initialization logic after the component is added to the DOM.
    2. When you want to – fetch data, set up event listeners, or set default values for component properties.
    3. When you want to – Subscribe or unsubscribe from a message channel.
    4. When you want to – Navigate to different page types like – record and list views using lightning/navigation module.

Explore the post below to learn about the five different lifecycle hooks in LWC.

Example

HTML (connectedCallbackDemo.html):

				
					<template>
    <lightning-card title="ConnectedCallback Example">
        <div>
            <p>Account Name: {accountName}</p>
        </div>
    </lightning-card>
</template>
				
			

JavaScript (connectedCallbackDemo.js):

				
					import { LightningElement, api, wire } from 'lwc';
import { getRecord } from 'lightning/uiRecordApi'; // (4) Using uiRecordApi
import { subscribe, unsubscribe, MessageContext } from 'lightning/messageService'; // (5) Subscribing to a message channel
import MY_MESSAGE_CHANNEL from '@salesforce/messageChannel/MyMessageChannel__c'; // Message channel import
import getAccountData from '@salesforce/apex/AccountController.getAccountData'; // (2) Calling Apex method

export default class ConnectedCallbackDemo extends LightningElement {
    @api recordId; // Exposed property for parent to pass recordId (1) Setting properties
    accountName; // Variable to hold account name (1) Defining variables

    subscription = null; // (5) To manage message channel subscription

    connectedCallback() {
        // (1) Setting properties and defining variables
        this.accountName = 'Default Account Name';

        // (2) Calling Apex method
        this.loadAccountData();

        // (4) Calling uiRecordApi
        this.fetchRecordDetails();

        // (5) Subscribing to a Lightning Message Channel
        this.subscription = subscribe(this.messageContext, MY_MESSAGE_CHANNEL, (message) => {
            this.handleMessage(message);
        });

        // (3) Dispatching a custom event
        this.dispatchEvent(
            new CustomEvent('connected', {
                detail: 'Component is initialized!',
                bubbles: true,
                composed: true,
            })
        );
    }

    disconnectedCallback() {
        // (5) Unsubscribing from the Lightning Message Channel
        if (this.subscription) {
            unsubscribe(this.subscription);
            this.subscription = null;
        }
    }

    // Helper method for (2) Calling Apex
    async loadAccountData() {
        try {
            const account = await getAccountData({ recordId: this.recordId });
            this.accountName = account.Name;
        } catch (error) {
            console.error('Error fetching account data', error);
        }
    }

    // Helper method for (4) Using uiRecordApi
    fetchRecordDetails() {
        const fields = ['Account.Name', 'Account.Phone'];
        getRecord({ recordId: this.recordId, fields })
            .then((record) => {
                console.log('Record fetched using uiRecordApi:', record);
            })
            .catch((error) => {
                console.error('Error fetching record using uiRecordApi', error);
            });
    }

    // Helper method for (5) Handling messages from Lightning Message Channel
    handleMessage(message) {
        console.log('Message received:', message);
    }

    @wire(MessageContext)
    messageContext; // Required for Lightning Message Service
}
				
			

Code Explanation:

1. Setting Properties and Variables:

    • Declared accountName and recordId properties inside connectedCallback().
    • Initialised accountName inside connectedCallback().

2. Calling Apex Methods:

    • loadAccountData() calls an Apex method to fetch account details.

3. Dispatching a Custom Event:

    • A CustomEvent is dispatched in connectedCallback() to notify parent components.

4. Calling uiRecordApi:

    • fetchRecordDetails() fetches record details using getRecord.

5. Subscribing to a Lightning Message Channel:

    • Subscribed to MY_MESSAGE_CHANNEL in connectedCallback() and unsubscribed in disconnectedCallback().

Key Points

    • connectedCallback() is the second hook in the LWC lifecycle, called after the constructor.
    • The DOM is available for use, but focus on lightweight operations.
    • Cleanup tasks related to the subscriptions or timers should be handled in disconnectedCallback.

Checkout below posts to explore other Lifecycle hooks in LWC in detail

Share This Article
Follow:
Chinmaya is working as a Senior Consultant with a deep expertise in Salesforce. Holding multiple Salesforce certifications, he is dedicated to designing and implementing cutting-edge CRM solutions. As the creator of Writtee.com, Chinmaya shares his knowledge on educational and technological topics, helping others excel in Salesforce and related domains.
4 Comments