Life Cycle of LWC
Lightning web components have their own lifecycle managed by the Salesforce framework. The framework creates components, inserts them into the DOM, renders them, and removes them from the DOM. It also monitors components for property changes. It Manages the flow of the related component (Parent to child and child to parent).
Below is the flow diagram of the default behavior of the LWC lifecycle and this determines the complete route of your LWC component navigation.
Note: A lifecycle hook is a JavaScript callback method triggered at a specific phase of a component instance’s lifecycle.
Let’s Break the Lifecycle flow of Lightning web component
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.
connectedCallback()
This method Called when the element is inserted into a document. In this phase, the hook flow executes from parent to child. As you can see in the diagram, You can’t access child elements in the component body because they don’t exist.
render()
Call this method to update the UI. It may be called before or after. Always the parent 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 render.
renderedCallback()
Called after every render of the component. This lifecycle hook is particular to Lightning Web Components. This hook generally flows from child component to parent component means bottom to top.
In this stage the component is rerendered 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.
Let’s explore it practically
Create the Parent Component
Parenthook.html
<template> hello parent hooks {sample} <c-childhooks></c-childhooks> </template>
Parenthook.js
import { LightningElement,api } from 'lwc'; export default class Parenthooks extends LightningElement { @api temp='temp1'; @api sample='hello'; constructor(){ super(); console.log('parent constructor call'); } connectedCallback(){ console.log('parent connected callback call'); } renderedCallback(){ console.log('parent render call back'); } disconnectedCallback(){ console.log('parent disconnected call back'); } render(){ console.log('parent render method'); if(this.temp=='temp1'){ return secondtemp; } else { return firsttemp; } } }
Childhooks.js (create new child component)
import { LightningElement } from 'lwc'; export default class Childhooks extends LightningElement { constructor(){ super(); console.log('child constructor call'); } connectedCallback(){ console.log('child connected callback'); } renderedCallback(){ console.log('child render callback'); } }