LWC-Life Cycle Hooks
3 min readMar 13, 2023
We all have heard this term when it comes to working in LWC.So let’s dive into it and get more clarity on this term.
What is a lifecycle hook?
Like in the Aura framework, we use init(), render(), rerender(), afterRender(), unrender() methods to handle the lifecycle of components.
Similarly, in Lightning web components we have javascript callback methods, that get triggered at different phases of the component’s instance lifecycle.
Now take a look at each life cycle hooks one by one.
constructor():
- Gets triggered when the component is created. It flows from the parent to the child component which means it fires in the parent component first. It is similar to the init() method in the aura component.
- It is necessary to invoke super() from the constructor since the Lightning web component extends LightningElement which has a constructor and is not supposed to bypass the parent class constructor.
connectedCallback():
- This hook comes into action when an element is inserted into the DOM.
- This also flows from parent to child. Using the isConnected property we can verify if the component is connected to DOM or not.
- We cannot access the child properties but we can access parent properties and modify them as well.
- We can also subscribe and unsubscribe from the Lightning Messaging Channel.
renderedCallback():
- This callback gets called multiple times during the lifecycle of the component. It gets called every time the component gets rendered.
- This hook flow from child to parent.
- To track if renderedCallback is executed we can make use of the boolean property called isRendered.
- The use of reactive property inside of the renderedCallback() can lead to an infinite loop.
render():
- Technically this is not considered the lifecycle hook in LWC.
- Being a developer we can use this to update the UI and it may get called before and after the connectedCallback().
- This flow from parent to child.
- Majorly this is used to conditionally render the html template and contains the logic to decide which template needs to be rendered.
- This is a protected method on the LightningElement class.
disconnectedCallback():
- It flows from parent to child.
- This callback gets called when the component is removed from the DOM.
- This hook can also be used to Unsubscribe from the Message Channel.
- The below diagram will make you understand the flow that happened when this component will get called.
errorCallback(error, stack):
- This callback gets triggered when any of the lifecycle hooks throw an error.
- In simple words, we can say it is similar to the javascript catch block containing error and stack as its arguments.
- error is a native javascript error object whereas stack is a string.