Chapter 23: connnectedCallback() in Lightning Web Component

Hello Friends, In this chapter we will go in details about connectedCallback() in Lightning Web Component.

init event handler in an Aura component is replaced with the standard JavaScript connectedCallback() method in a Lightning web component.

We use the init event in an Aura component to initialize a component after component construction but before rendering.

<aura:handler name="init" value="{!this}" action="{!c.doInit}"/>

The doInit function in the component’s controller performs necessary initialization.

({
doInit: function(cmp) {
// initialize component
}
})

In a Lightning web component, use connectedCallback() instead in the component’s JavaScript file.

Sample

import { LightningElement } from 'lwc';
export default class App extends LightningElement {

connectedCallback() {
// initialize component
}
}

The connectedCallback() hook can fire more than once. For example, if you remove an element and then insert it into another position, such as when you reorder a list, the hook fires several times. If you want code to run one time, write code to prevent it from running twice.

Use of ConnectedCallback()

We generally use it when we need to do something when the component is loaded. Example: query some data when the component is loaded.

The execution flow of connectedCallback is parent to child. So we cannot access child elements in the connectedCallback, because they are not inserted yet.

app.html

<template>
<lightning-input label="Name" value={greeting}>
</lightning-input>
</template>

app.js

import { LightningElement} from 'lwc';

export default class App extends LightningElement {

    connectedCallback(){
        console.log('connectedcallback');
        this.greeting ='sfdcAmplified';
    }
}

Demo: Connected Callback in Lightning Web Component

Here, we are setting the value of input field to sfdcAmplified every time it loads.

 

I hope you enjoyed the chapter!

 

Together we can learn faster !

Join LWC study group on Telegram 

Subscribe to Youtube channel and blog to get latest updates

 

Reference:

LWC Migrate Initializers

Did you enjoy this article?
Signup today and receive free updates straight in your inbox.
I agree to have my personal information transfered to MailChimp ( more information )
50% LikesVS
50% Dislikes