Salesforce Technical Guides

Lifecycle Hooks in LWC

User Salesforce Dev Team
Calendar October 06, 2022

Its very common to notice that developers tend to skip the in-depth analysis of the lifecycle of LWC. The reason is that by just adding the connectedCallback and renderedCallback problem gets solved. It does get solved, but what about the best practices? Since LWC is new, it becomes imperative to know the best practices for this one.

Do you know we also have a render callback to load templates specifically?
This blog comprises a mix of a handful of POCs and theoretical details that can become your go-to guide regarding LWC lifecycle hooks.

null

1. constructor()

This method calls when the component is first created. The flow of this method is from the parent component to the child component. In this phase, we can’t access child elements in the component body because they don’t exist by that time. Even Properties are not passed.

2. connectedCallback()

This method Called when the element is inserted into a document. In this phase, the hook flow executes from parent to child. You can’t access child elements in the component body because they don’t exist.

3. render()

Call this method to update the UI. It may be called before or after. Always the parent is rendered first in the flow. After rendering the parent, it jumps to the child constructor and follows the same steps as the parent did earlier till the child renders.

import { LightningElement,track } from 'lwc';
import signup from './signUp.html';
import login from './loginPage.html';
export default class LoginPage extends LightningElement {
@track page='';
hasRendered=false;
constructor(){
super();
}
render(){
if(this.page==='temp1'){
this.hasRendered=true;
return signup;
}else{
this.hasRendered=true;

return login;
}
}
handleSignUp(){
this.page='temp1';
}
handleLogin(){
this.page='temp2';
}
back(){
this.page='temp2';
}
afterSignUp(){
alert('refresh the page to login!');
}
}

 4. renderedCallback()

Called after every render of the component. This hook generally flows from the child component to the parent component means bottom to top. In this stage, the component is re-rendered when the value changes and that property is used either directly in a component template or indirectly in the getter of a property used in a template.

5. disconnectedCallback()

Called after every render of the component. This hook generally flows from the child component to the parent component means bottom to top. In this stage the component is re-rendered when the value 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.

6. errorCallback()

It Captures errors that may happen in all the child components lifecycle hooks. This method is unique to LWC. It has two parameters error and stack. The error argument is a JavaScript native error object, and the stack argument is a string.

Error in parent shows in UI no boundary component for it. This means if there is an error in the child, the parent handles the error, but if there is an error in the parent, it is shown in the UI. This method works like a JavaScript catch() block for catching errors.

How do things actually work when the page gets loaded?

  • Constructor of parent gets called.
  • Parent’s connectedCallback gets called.
  • Render method gets called.
  • Constructor of child gets called.
  • Child’s connectedCallback gets called.
  • Child’s renderedCallback gets called.
  • Parent’s renderedCallback gets called.
  • Parent’s disconnectedCallback gets called.
  • Child’s disconnectedCallback gets called.

Some essential pointers to prevent errors and conflicts

Things to remember when working with the constructor: 

  • Don’t use a return statement inside the constructor body, unless it is a simple early-return (return or return this).
  • Don’t use the document.write() or document.open() methods.
  • Don’t inspect the element’s attributes and children, because they don’t exist yet.
  • Don’t inspect the element’s public properties, because they’re set after the component is created. Don’t Add Attributes to Host
  • Element During Construction

Things to remember when working with ConnectedCallback:

  • Use connectedCallback() to interact with a component’s environment.
  • For Example – Establish communication with the current document or container and coordinate behavior with the environment or
  • Perform initialization tasks, such as fetch data, set up caches, or listen for events (such as publish-subscribe events)

Things to remember when working with RenderedCallback

  • renderedCallback() updates an @track and @wire property, which triggers a render.
  • Use renderedCallback() to understand the state of the “inside” world (a component’s UI and property state).

Things to remember when working with Render

Example -> Let’s say we have the parent component Shapes and child component Rectangle and circle

import { LightningElement,api } from 'lwc';
import firstTemplate from './rectangle.html';
export default class Rectangle extends LightningElement{
@api length; @api breadth; @api aor;
constructor(){
super();
console.log('constructor-rectangle');
}
connectedCallback(){
console.log('connectCallback-rectangle');
}
renderedCallback(){
console.log('renderedCallback-rectangle');
}
disconnectedCallback(){
console.log('disconnectedCallback-rectangle');
}
finalAreaRectangle(){
this.aor=this.length*this.breadth;
}
render(){
return firstTemplate;
}
}

import { LightningElement,api } from 'lwc';
import firstTemplate from './circle.html';
export default class Circle extends LightningElement{

@api radius; @api area;
constructor(){
super();
console.log('constructor-circle');
}
connectedCallback(){
console.log('connectCallback-circle');
}
renderedCallback(){
console.log('renderedCallback-circle');
}
disconnectedCallback(){
console.log('disconnectedCallback-circle');
}
finalArea(){
this.area=3.14*this.radius*this.radius;
}
render(){
return firstTemplate;
}
}
import { LightningElement } from 'lwc';

export default class Shapes extends LightningElement{
constructor(){
super();
console.log('constructor-shapes');
}
connectedCallback(){
console.log('connectCallback-shapes');
}
renderedCallback(){

console.log('renderedCallback-shapes');
}
disconnectedCallback(){
console.log('disconnectedCallback-shapes');
}
}

Output: 

 

Thanks for reading, and let us know your thoughts in the comment section.

For more Salesforce and MuleSoft tutorials, please check Caelius Consulting’s Resource Centre.

 

 

Leave a comment

Your email address will not be published. Required fields are marked *