Lifecycle Hooks pt. 2

By in
320
Lifecycle Hooks pt. 2

Flowing from parent to child are both hooks. Because they are not yet created, child components cannot be accessed from callbacks. Use this to gain access to the host element. Use this.template to gain access to a component’s template’s elements.

To communicate with the environment of a component, use connectedCallback(). Consider using it for:

  • Communication with the current document or container should be established, and behaviour should be in accordance with the surroundings
  • Get data, create caches, or listen for events as initialization activities.
  • Subscribe and Unsubscribe from a Message Channel.
Components and Hook
Image Source: Developer.Salesforce

The first properties supplied to the component trigger the connectedCallback() hook. It is preferable to write the logic in a setter rather than a connectedCallback if a component draws its internal state from its properties ().

The connectedCallback() hook has a multiple-fire capability. The hook fires multiple times, for instance, if you delete an element and subsequently add it to a different location, as when you rearrange a list. Write code to stop it from executing more than once if you only want it to execute once.

To finish tasks started in connectedCallback(), such as clearing caches or deleting event listeners, use disconnectedCallback(). It is only possible to use renderedCallback() with Lightning Web Components. After a component has finished rendering, use it to execute logic.

The expressions in the template are reevaluated when a component renders. A modification (or mutation) to a component’s state after it has been connected and rendered designates the component as dirty and queues a microtask to re-render the component.Throughout the life of an application, a component is typically rendered numerous times. Utilize a boolean property like hasRendered to track if renderedCallback() has been called if you want to use this hook for a one-time activity.

 

Conclusion

In this way, it’s important to stop the rendering code everytime a component is rerendered for that we set hasRendered to true and perform the one-time operation when renderedCallback() first runs. We don’t execute the operation if hasRendered = true.

 

Additional Resources

Cover Photo by Firdouss Ross on Unsplash

Leave a reply

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