Life Cycle of a Lightning Web Components
Lightning Web Component is built on a component-based framework, it's extremely important that we understand the Life Cycle events of a Component to build better components.
Let's take a couple of components and understand what happens steps by step.
Here is the template file.
And this is the associated controller file storeFront.js
.
Regarding the child component here it is.
Last, here is the controller.js
file
Now, here are the things that happen in sequential order when a page is loaded, let's say a record page which has <c-store-front></c-store-front> embedded in it.
- An instance of StoreFront component is created, hence, the constructor is invoked (make sure you don't miss out on the super() in the constructor()).
- If the component has any @api enabled properties, they will be assigned data.
- StoreFront component is connected to the main
DOM
. - The connectedCallback() in StoreFront is invoked.
- StoreFront component is rendered (It is not going to invoke renderedCallback())
- A check is performed to see if there are any child components, if it exists, the constructor of that component will be invoked which is going to be Cake component in this case.
- If Cake component has any @api enabled properties, they will be assigned data.
- Cake component is connected to
DOM
. - The connectedCallback() in Cake is invoked.
- Cake Component is rendered completely.
- Cake component is rendered and the associated renderedCallback() life cycle hook is invoked.
- Once it's completed, it takes the same route it took to arrive here. The renderedCallback() of the StoreFront is invoked.
Here are the console logs in chrome browser that gives us a visual confirmation regarding the same.