Life Cycle Hooks in LWC

Life Cycle hooks in LWC are in a way similar to the constructor in Apex Class and init and render handlers in Aura Components.

During various stages of a life cycle of a component different pre-defined methods are invoked and this is how the list goes.

  • constructor()
  • connectedCallback()
  • renderedCallback()
  • disconnectedCallback()
  • errorCallback()

Let's try to understand one after the other.

Constructor()

Constructor Life Cycle Hook is the one that gets invoked when the instance of the component is created.

As a mandate, we need to invoke super() from the constructor. As every LWC component extends LightningElement and since LightningElement has a constructor, we are not supposed to bypass invoking that parent constructor.

import { LightningElement } from 'lwc'

export default class HelloWorld extends LightningElement{
	constructor(){
    	super();
    }

}
constructor() Life Cycle Hook in LWC

connectedCallback()

The moment the component is connected to the DOM this life cycle hook is invoked. By the time this method is invoked, all the @api properties would have received the data from the parent and we can use that data to make a call to Apex method.

import { LightningElement } from 'lwc'

export default class HelloWorld extends LightningElement{
	connectedCallback(){
    	console.log('CONNECTED CALLBACK');
    }
}
connectedCallback() Life Cycle Hook in LWC

renderedCallback()

Once the component is completely rendered that's when this Life Cycle Hook in LWC gets invoked. Since the complete component is rendered we can have some business logic that involves the DOM.

import { LightningElement } from 'lwc'

export default class HelloWorld extends LightningElement{
	renderedCallback(){
    	console.log('RENDERED CALLBACK');
    }
}
renderedCallback() Life Cycle Hook in LWC

disconnectedCallback()

When you want to have some logic that has to be executed when the component is destroyed this Life Cycle Hook in LWC comes handy.

One situation where I can think of using this Life Cycle Hook in LWC is when you want to unsubscribe to the message channel.

import { LightningElement } from 'lwc'

export default class HelloWorld extends LightningElement{
	disconnectedCallback(){
    	console.log('DISCONNECTED CALLBACK');
    }
}
disconnectedCallback() Life Cycle Hook in LWC

errorCallback()

This is pretty much straight forward when there is an error in the process of instantiating the component, connecting or rendering the component this Life Cycle Hook gets fired up.  

import { LightningElement } from 'lwc'

export default class HelloWorld extends LightningElement{
	errorCallback(){
    	console.log('ERROR CALLBACK');
    }
}
errorCallback() Life Cycle Hook in LWC