Thursday, 20 May 2021

Lifecycle Hooks - Lightning Web Component

INTRODUCTION

A lifecycle hook is a JavaScript callback method which is called at a certain point in the lifecycle of a component instance. The components' lifetime was managed using the Aura system's init(), render(), rerender(), afterRender() and unrender() methods. In Lightning Web Component, callback methods are used to manage the components' lifespan, Lifecycle hooks are what they're called. You can adjust the actions by overriding these hooks. There are various life cycle hook methods to pick from, and we will go through each one in detail in this blog.

Here are the Types of lifecycle hooks

1. Constructor():

  • Whenever a component instance is created, this hook is invoked. 
  • The first statement must be super() with no parameters. 
  • Don’t use a return statement inside the constructor body.
  • This hook flows from parent to child, which means that it fires in the parent first. You can't access child elements because they don't exist yet. Properties aren't passed yet, either.
  • Properties are assigned to the component after construction and before the connectedCallback() hook.
  • The similarity of this hook in Aura is with init() event but init() Aura event flows from child to parent.


sample code

import { LightningElement } from 'lwc';
export default class App extends LightningElement {
constructor() {
super();
console.log('Run Code When a Component Is Created');
}
}
view raw constructor.js hosted with ❤ by GitHub

2. connectedCallback():

  • it fires when a component is inserted into the DOM. 
  • The connectedCallback() hook can be fired more than one time.
  • This hook flows from parent to child. You can’t access child elements because they don’t exist yet. 
  • Use connectedcallback() to interact with a component's environment. For example, you can utilize it for:
    • Establishing communication with the current document or container and coordinate behavior with the environment. 
    • Performing initialization tasks, such as fetch data, set up caches, or listen for events.
    • Subscribe and Unsubscribe from a Message Channel.


SAMPLE CODE

import { LightningElement, track, api} from 'lwc';
export default class App extends LightningElement {
list=[];
constructor() {
super();
console.log('Run Code When a Component Is Created');
}
connectedCallback() {
this.list.push('component');
console.log('Run Code When a Component Is Inserted or Removed from the DOM');
console.log(this.list);
}
}

3. disconnectedCallback():

  • Invoked when the element is removed from a DOM. 
  • This hook flows from parent to child.
  • Use disconnectedCallback() to clean up work done in the connectedCallback(), like purging caches or removing event listeners.
  • You can also use this hook to unsubscribe from a message channel.

SAMPLE CODE

import { LightningElement, track, api } from 'lwc';
export default class App extends LightningElement {
list=[];
constructor() {
super();
console.log('Run Code When a Component Is Created');
}
connectedCallback() {
this.list.push('component');
console.log('Run Code When a Component Is Inserted or Removed from the DOM');
console.log(this.list);
}
disconnectedCallback() {
this.list=[]
console.log('Use to clean up work done in the connectedCallback()');
}
}

4. render():

  • To update UI, we can call this method. It may be called before or after connectedCallback().
  • It is rare for a portion to be referred to as render(). The most typical use is to apply correct template (HTML file) based on business logic. The method must return correct HTML template. 
  • For example, imagine that you have a component that needs to be rendered in two different ways but you don’t want to mix it in one HTML file. So, here we can create multiple HTML files in the component bundle. And then Import  them and add a condition in the render() method to return the correct template depending on the component's state.

SAMPLE CODE


FirstTemplate.HTML
<!-- FirstTemplate.HTML -->
<template>
<h1>This is FirstTemplate!</h1>
<lightning-buttononclick={change} label="SecondTemplate" name="click">
</lightning-button>
</template>
SecondTemplate.HTML
<!-- SecondTemplate.HTML -->
<template>
<h1>This is SecondTemplate!</h1>
<lightning-buttononclick={change} label="FirstTemplate" name="click">
</lightning-button>
</template>
App.HTML & App.js
<!-- App.HTML -->
<template> </template>
<!-- App.js -->
import { LightningElement, track, api } from 'lwc';
import firstpage from './FirstTemplate.HTML';
import secondpage from './SecondTemplate.HTML';
export default class App extends LightningElement {
list=[];
@api page = firstpage;
constructor() {
super();
console.log('Run Code When a Component Is Created');
}
connectedCallback() {
this.list.push('component');
console.log('Run Code When a Component Is Inserted or Removed from the DOM');
console.log(this.list);
}
disconnectedCallback() {
this.list=[];
console.log('Use to clean up work done in the connectedCallback()');
}
change() {
if(this.page== firstpage)
this.page= secondpage;
Else
this.page= firstpage;
}
render() {
if(this.page== secondpage)
return firstpage;
Else
return secondpage;
}
}
view raw app.js hosted with ❤ by GitHub

5. renderedCallback():

  • it is called after rendering of every component. This lifecycle hook is specific to Lightning Web Components, it is not from the HTML custom elements specification. This hook flows from child to parent.
  • A component is rerendered when the value of property changes and that property is used either directly in a component template or indirectly in the getter of a property that is used in a template.
  • As this hook is called after every render of the component, we need to be careful if we perform some action in specific condition. It should be guarded with the condition that doesn't trigger an infinite rendering loop.


SAMPLE CODE

import { LightningElement } from 'lwc';
export default class Parent extends LightningElement {
constructor(){
super();
console.log('Run Code When a Component Is Created');
}
connectedCallback() {
console.log('Run Code When a Component Is Inserted or Removed from the DOM');
}
renderedCallback(){
console.log('Run Code When a Component Renders');
}
}

6. errorCallback(error,stack):

  • It captures the errors that may occur in the lifecycle hooks of all descendant components.
  • The error argument is a JavaScript native error object and stack parameter is a string.


SAMPLE CODE

import { LightningElement } from 'lwc';
export default class Parent extends LightningElement {
errorCallback(error, stack) {
console.log('Error Message:-'+error);
console.log('Stack Message:-'+stack);
}
}


summary


The framework manages the lifespan of Lightning web components. When the state of a component changes, the framework generates components, adds and removes them from the DOM, and renders DOM modifications. 

If you have any questions you can reach out our Salesforce Consulting team here.

No comments:

Post a Comment