Lifecycle Hooks pt. 1

By in
344
Lifecycle Hooks pt. 1

When a component instance is created, the constructor() method is called. Avoid adding properties to the host element while it is being built. In any other lifecycle hook, you can provide the host element additional properties.

From parent to kid, the function constructor() flows.

The function constructor() must adhere to these specifications from the HTML: Custom elements specification.

 

  • Super() with no parameters must be used as the initial statement. The appropriate prototype chain and value are established by this call. Super() must always be called before touching this.
  • Use a return statement only if it is a straightforward early-return outside of the function constructor() body (return or return this).
  • The document.write and document.open methods should not be used.
  • The element’s children and attributes have not yet been created, so avoid looking at them.
  • The element’s public properties are set after the component is formed, so avoid looking at them.
Component and Lifecycle Hooks
Image Source: Developer.Salesforce

 

Don’t add attributes to the host element while it is being built.

Any stage of the component lifecycle other than building allows for the addition of attributes to the host element.

This example violates the law since it adds an attribute to the constructor host element.

 

import { LightningElement } from ‘lwc’;

export default class WgDeprecated extends LightningElement {

constructor() {

super();

this.classList.add(‘new-class1’);

}

}

 

Since this example adds an attribute to the host element in the connectedCallback, it is acceptable ().

 

 

import { LightningElement } from ‘lwc’;

 

export default class WgNew extends LightningElement {

connectedCallback() {

this.classList.add(‘new-class’);

}

}

 

A component’s insertion into the DOM triggers the connectedCallback() lifecycle hook. When a component is deleted from the DOM, the lifecycle hook disconnectedCallback() is triggered.

 

Conclusion

In this way, we understood that it is best to use connectedCallBack() lifecyle hook when we need to access the DOM or public attributes of a lightning web component.

 

To learn more about Lightning Web Components and other related features, check out some of my related blogs below!

 

Additional Resources

Cover Photo by Matheo JBT on Unsplash

Leave a reply

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