Mastering LWC Connected Callback

Telegram logo Join our Telegram Channel
Lwc connectedCallback lifecycle hook

What is connectedCallback()

The connectedCallback() function is one of the important LifeCycle hooks of Lightning web components. 

The connectedCallback() lifecycle hook is automatically invoked whenever a component is inserted into the Document Object Model (DOM). It allows us to run the code after the component is added to the page.

The execution flow of connectedCallback is parent to child. So you cannot access child elements in the connectedCallback, because they are not inserted yet. This also means the connected callback of the parent component gets called before the child component's.

The connected callback is the ideal place to:

  • Initialize the components: We can set default values to the properties of the components.
  • Fetch Data: You can fetch data from external sources using Apex or JavaScript libraries.
  • Set up Event Listeners: If you using any pub-sub library like CometD or LMS, use the connectedCallback to attach the event listers to the component.
  • Perform any other initialization logic: This could include setting up timers, initializing state variables, or performing any other logic that needs to happen after the component is inserted into the DOM.
  • Read data from cache: This could be the scenario where you want to read from local storage, session storage, etc. For more information see my post Client Side Caching in LWC with local storage.


Syntax of connected callback

Connected callback syntax is very simple. You just need to create a function with the name connectedCallback.

connectedCallback() {
    // add your logic here
}


Example: Fetching Data with Apex

As discussed above there are various applications of connected callback lifecycle hook of LWC. Let us understand the concept with one such example.

For this example, I want to fetch the component configuration stored in a Custom Metadata Object. Now, let us see the apex code.

connectedCallback() {
  // Define the data variable to store the retrieved data
  this.config = [];

  // Fetch data from the MyConfig__mdt object using imperative call
  getRecords({
    recordType: 'MyConfig__mdt'
  }).then((records) => {
    // Loop through each record and populate the data variable
    for (let i = 0; i < records.length; i++) {
      this.config.push(records[i]);
} }).catch((error) => { console.error(error); }); }

In the above code, the getRecords apex function is called imperatively. Whenever the component is inserted into DOM, the config property will filled with data from Apex. This information then be used for the entire life of the component.


Caveats with Connected Callback

  • The connectedCallback() hook can fire more than once. For example, if you remove an element and then insert it into another position. If you want code to run only once, then write code to prevent it from running twice
  • Child components are not available to access in the connectedCallback().
  • Although you can perform DML operations in connected callback it is best practice to avoid that.

Best Practices for Using connectedCallback()

Here are some best practices for using connectedCallback():

  • Avoid expensive operations: Don't perform any expensive operations, such as long-running Apex calls, within connectedCallback(). This can impact the performance of your application. 
  • Keep it clean: Use connectedCallback() for initialization logic and avoid putting too much logic within it.
  • Follow the lifecycle flow: Understand the order of the lifecycle hooks and use them accordingly.
  • Document your code: Document your code to explain what happens in connectedCallback() and why.
  • If you have attached any event handlers to your component, it is always best practice to unlink/destroy any event handlers in the disconnected callback.

No comments :
Post a Comment

Hi there, comments on this site are moderated, you might need to wait until your comment is published. Spam and promotions will be deleted. Sorry for the inconvenience but we have moderated the comments for the safety of this website users. If you have any concern, or if you are not able to comment for some reason, email us at rahul@forcetrails.com