Hello! 👋 Salesforce Lightning Web Components (LWC) offer
a contemporary, efficient framework for creating interfaces on the Salesforce
platform. The component's lifecycle is pivotal, enabling developers to execute
code at distinct stages like initialization, rendering, and destruction. In
this piece, we'll delve into LWC's lifecycle hooks, offering examples for
seamless integration into your projects.
How do lifecycle hooks work in lightning web components?
Lightning web components have a lifecycle managed by the framework. When lightning web component instance is created it goes through a lifecycle phase. During specific phases, a lifecycle hook fires triggering a particular callback method. Each callback method has it’s specific use and has things you can and cannot do.
Overall framework basically can do the following.
- create the component
- insert the component into the DOM
- renders the component
- removes component from the DOM
- monitors component for property changes
Starts with parent component creation, insertion to the DOM, render and child component creation, insertion to the DOM and render. Finally child calls renderedCallback and then calls the parent’s renderedCallback.
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
إرسال تعليق