Andy Tran

Lifecycle Hooks in LWC

by | 25 Mar, 2022 | Salesforce | 2 comments

hooks lwc

The Lightning Framework manages the lifecycle of lightning web components, It is responsible for creation, insertion of components into the DOM and renders them and also removes them from the DOM. It also monitors the rendered components for any changes in the properties. 

Lifecycle Hooks are callback methods that are triggered at a specific phase of a component instance’s lifecycle. A hook method tells us that something happened and it may or may not exist on the prototype chain. There are a total of 6 lifecycle hooks in LWC.

Let’s see the flow of lifecycle hooks execution by diagram given below:

Life Cycle Hook in LWC

Let’s understand each of these lifecycle Hooks.

1. Constructor() 

constructor() is called when the instance of a component is created. In this phase we have no access to the public properties(decorated with @api) of the component as they are not yet in existence, also if we have included a child component inside our component then we can’t access the elements of the child component because the flow of this method is from parent component to the child component. That is, the child component will be initiated after the parent component is initiated. Below given examples show how we can use constructor in the file of LWC.

Life Cycle Hook in LWC

As a necessary step we need to call the super() keyword from constructor(). As every LWC component extends LightningElement  which has its constructor and we are not supposed to bypass calling the parent class’s constructor.

We can set values from the Constructor but the best practice is to get or set the value of the variable using the getter and setter method. Refer below given example to understand it better.

Life Cycle Hook in LWC

Here we are using getter and setter to get and set the value.

There are few Do’s and Don’t with constructor:

DO’S

  • Use navigation services. Note: services like show toast message is not valid because it uses dispatchEvent and it is not allowed in the constructor.
  • Set the value of properties and also can define the variable.
  • Call an apex method.
  • Call UI APIs like uiRecordApi.

DON’T

  • Don’t try to access the element’s attributes because they don’t exist yet.
  • Cannot create and dispatch custom events from the constructor.
  • Cannot manipulate the DOM.

2. ConnectedCallback()

It is called when the component is inserted into the DOM. By the time this method gets executed all the public properties would have received the value from their parent component. In this method we can call the apex method which requires the public properties as a parameter as of now public properties are in existence.

If we want to perform any kind of logic after the component gets loaded into DOM we can use connectedCallback() lifecycle method.

The flow of this method is from the parent component to the child component.

Life Cycle Hook in LWC

To check whether the component is connected to DOM or not we can use isConnected property which returns true if component is connected otherwise returns false. Example to check the same is shown below. 

ConnectedCallback Example

OUTPUT on Console

ConnectedCallback Output

DO’S

  • Fire a custom event.
  • Call UI APIs & use navigation service.
  • Subscribe and Unsubscribe from a Message Channel.
  • Access the elements of the component. Note that we do not have access to any child component’s elements as till now they are not in existence.

DON’T

  • Cannot access the elements of the child component because they don’t exist yet. 

3. render()

It gets executed after the connectedCallback method execution finishes, which overrides the standard rendering functionality of LWC. We can control the rendering process by conditionally rendering the template (html file) on the basis of business logic or a few conditions. It must return a valid html template file and this html file is rendered on the screen.

Technically speaking render() is not a lifecycle hook, it is a protected method on the LightningElement class.

The flow of this method is from the parent component to the child component.

Let’s see how conditional rendering works. We have one component named parentLWC, which contains 5 files in it:

parentLWC.html

Life Cycle Hook in LWC

parentLWC.js

Life Cycle Hook in LWC

parentLWC.js-meta.xml

render-js-meta

websitePage.html

render-website-html

showErrorPage.html

Life Cycle Hook in LWC

OUTPUT

The value of property error was false, thus website.html get rendered

renderCallback Output

4. renderedCallback()

It gets executes after a component is completely rendered on screen. renderedCallback is unique to LWC and the rest are from HTML custom elements specification. It should be guarded with conditions that do not trigger an infinite rendering loop as this hook is called after every render of the component. A component is rerendered when the value of a property changes.

The flow of this method is from the child component to the parent component, meaning it follows a bottom to top approach. Below example shows how the renderedCallback() works.

We have two components, parentLWC and childLWC.

Parent component

Note: we are rendering the websitePage.html via render() hook.

parentLWC.html

Life Cycle Hook in LWC

websitePage.html

renderedCallback-webpage-html

parentLWC.js

renderedCallback-js

Child component

childLWC.html

Life Cycle Hook in LWC

childLWC.js

renderedCallback-child-js

Output logs:

Thus, it is clear that the child component is rendered first then the parent component gets rendered. 

renderedCallback-output

renderedCallback() method is called multiple times which result in useless rendering of the page, to make sure that renderedCallback() is called only when it is required and for that we can use private boolean property. Its shown in following example:

renderedCallback-output

DO’S

  • Perform business logic after a component has finished the rendering phase.
  • Access the elements of the component.
  • Call an Apex method.
  • Create and Dispatch custom events.
  • Call UI APIs with show toast events.
  • Call navigation services.

DON’T

  • Don’t use renderedCallback() to change the state of a component that is setting properties value, always use getter and setter.
  • Can’t update a wire adapter configuration object property in renderedCallback(), as it can result in an infinite loop.
  • Don’t update a reactive property or field in renderedCallback(), as it can result in an infinite loop. 

5. disconnectedCallback()

It gets executed when a component is removed from the DOM. It is the best place to write the logic which needs to be achieved after a component is destroyed or removed from the DOM.

Life Cycle Hook in LWC

Let’s say our component has subscribed to the Lightning message service(LMS) channel to receive data from another LWC, we can unsubscribe to this channel in disconnectedCallback().

Life Cycle Hook in LWC

As shown in the above image we are calling the unsubscribeToMessageChannel() method inside disconnectedCallback() hook to unsubscribe the LMS channel. Also in the code it shows for the reference, how we can subscribe to the LMS channel.

DO’S

  • Remove the caches.
  • Remove the event listeners.
  • Unsubscribe LMS channels.

6. errorCallback(error, stack)

It gets executed when failure or error is captured during the lifecycle phases in all the descendent components in the tree. It is unique to LWC and the rest are from HTML custom elements specification. By this hook we can have an error boundary to our component.  It helps us to log the stack information and render an alternative template if error is encounters in the child component. So that users can get the idea exactly what happened and what to do next.

It is similar to the javaScript catch{} block for components that throw errors in child component lifecycle hooks. Yes, the error boundary component catches errors only from the lifecycle hooks of the children component, and not from itself.

It takes two arguments: error and stack. error is a javaScript native error object and stack is a string.

In the following example we are controlling the view by the error boundary which is created in the html file by us. If an error is encountered, the showErrorPage will get rendered, otherwise the websitePage will get rendered.

parentLWC.html

errorCallback-HTMl

parentLWC.js

errorCallback-Js

Thankyou for reading so far. Also Visit this link to read a Blog on Basics of LWC.

Keep learning!

Thank you for taking the time to read our blog. We have great confidence that you have found our ideas and processes to be of great value. If your company is currently in need of Salesforce-related services, we are delighted to offer our expertise. Erudite Works is widely recognized as one of the top sales cloud consultants. Our team has extensive experience in offering expert strategies, implementing, and customizing Salesforce CRM to effectively meet your business’s automation and reporting needs. Rest assured, our team holds certifications in all the necessary Salesforce modules, ensuring a seamless CRM solution and the delivery of exceptional consulting services. We invite you to contact us to learn more about our services.

Share this article...

2 Comments

  1. Jayant Sharma

    It is the one of most difficult part of LWC and was unable to find any resource for same. Thankyou for making this topic look so easy and understandable for me.

    Reply
  2. Hetvi

    Really very nice content and helpful to understand concept of Lwc HookLifeCycle

    Reply

Submit a Comment

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


The reCAPTCHA verification period has expired. Please reload the page.