Lightning Web component Lifecycle Hooks:

These are the callback methods that execute at a specific phase of the Lightning Web component’s lifecycle. There are various types of lifecycle hooks:

  1. constructor(): This method executes whenever the web component is initialized. The flow of execution is from parent to child.
  2. connectedCallback(): This method executes whenever the web component is inserted into DOM and it can fire more than once. We can modify the elements of the parent component in this callback method. It executes from parent to child.
  3. disconnectedCallback(): This method executes whenever a component is removed from the DOM. This method flows from parent to child. It also clears the array when it is fired.
  4. render(): This method is used whenever we develop a complex component. We use this method when we want to import different templates/components dynamically into our main component. This is used for conditional rendering. It will return a valid HTML template.
  5. renderedCallback(): Whenever any element of a component is rendered, this method is invoked. The flow of execution is from child to parent.
  6. errorCallback(error, stack): whenever any descendant/child component throws an error, this method will get executed. This method captures only the child component, and not from itself.

    • Error: This argument is a JavaScript native error object.
    • Stack: This argument holds a string value.

Here is the basic sample code of all the lifecycle hooks in LWC:
import { LightningElement } from 'lwc';
export default class HooksExamples extends LightningElement {
myName = 'Anjana';
constructor() {
super();
console.log('constructor');
}
connectedCallback() {
console.log('connectedCallback');
}
disconnectedCallback() {
console.log('disconnectedCallback');
}
/*render(){
}*/
renderedCallback() {
console.log('renderedCallback');
}
errorCallback(error, stack) {
console.error(error);
}
}

Advertisement

Webner Solutions is a Software Development company focused on developing Insurance Agency Management Systems, Learning Management Systems and Salesforce apps. Contact us at [email protected] for your Insurance, eLearning and Salesforce applications.

Please click here to read the original article as posted on Webner Blogs – eLearning, Salesforce, Web Development & More.

We source the web to bring you best Salesforce articles for our reader’s convenience. If you want to have this article removed, please follow guidelines at Digital Millennium Copyright Act (DMCA)..