Friday, March 1, 2024

Lifecycle Hooks in LWC (Lightning Web Components)

 A lifecycle hook is a callback method which is called automatically at a specific phase of a component lifecycle. These are managed by LWC framework. These hooks get called at different phases like initialization of components, when elements gets inserted in DOM or removed from DOM, rendering of components based on property changes etc.

Lets go through different lifecycle hooks:

constructor()

  • Whenever component is created, this function gets called.
  • This hook flows from parent to child, which means that it fires in the parent first.
  • As child element do not exist, you cannot access them.
  • Properties are mainly assigned to component after constructor() and before connectedCallback()
  • If you define constructor() callback then you should always super() from constructor(). This is because every LWC component extends LightningElement and since LightningElement has its own constructor, so we should first invoke the parent constructor.
import { LightningElement } from 'lwc'
export default class ConstructorCallbackExample extends LightningElement{
	constructor(){
		super();
	}
}


connectedCallback()

  • When the element is inserted into a document, this function gets called.
  • This hook flows also from parent to child. So you can’t access child elements because they don’t exist yet.
  • Properties are assigned to component so this callback can be used to perform or fetch initial data set.
  • If you manipulate the elements means adding or removing element from component, then connectedCallback() will fire more than once. So always put some checks if you don’t want to run particular logic everytime.
  • connectedCallback() can be used to Subscribe and Unsubscribe from a Message Channel.
import { LightningElement } from 'lwc'
export default class ConnectedCallbackExample extends LightningElement{
	connectedCallback(){
		console.log('***connected callback is called');
	}
}


renderedCallback()

  • renderedCallback() gets called after every render of component. Whenever value of reactive component changes, component get rendered.
  • renderedCallback() is specific to LWC and it has no dependency in HTML custom elements specifications.
  • renderedCallback() flows from child to parent.
  • Remember, updating state of component can cause infinite loop. So don’t update a public property or field in renderedCallback(). If you perform changes to reactive attributes, guard them or they can trigger wasteful rerenders or an infinite rendering loop.
  • Also don’t update a wire adapter configuration object property in renderedCallback(). 

disconnectedCallback()
  • Whenever an element is removed from DOM, then disconnectedCallback() is called.
  • This hook flows from parent to child.
  • Use disconnectedCallback() to clean up work done in the connectedCallback(), like purging caches or removing event listeners or unsubscribe from a message channel.
import { LightningElement } from 'lwc'
export default class disconnectedCallbackExample extends LightningElement{
	disconnectedCallback(){
    	console.log('**** disconnectedCallback is called');
    }
}

render()
  • If there is need to display different UI to end user based on some conditions, then we can have 2 different HTML files and decide which HTML file to render based on conditions.
  • Render() may be called before or after connectedCallback().
  • Imagine that you have a component that can be rendered in two different ways but you don’t want to mix the HTML in one file. Create multiple HTML files in the component bundle. Import them both and add a condition in the render() method to return the correct template depending on the component’s state.
  • Although it’s possible for a component to render multiple templates, it is recommended to use  lwc:if|elseif|else directives to render nested templates conditionally instead.
import { LightningElement } from "lwc";
import templateOne from "./templateOne.html";
import templateTwo from "./templateTwo.html";
export default class MiscMultipleTemplates extends LightningElement {
  showTemplateOne = true;
  render() {
    return this.showTemplateOne ? templateOne : templateTwo;
  }
  switchTemplate() {
    this.showTemplateOne = !this.showTemplateOne;
  }
}


errorCallback(error, stack)
  • The errorCallback(error, stack) hook is called when the component throws an error.
  • The error argument is a JavaScript native error object, and the stack argument is a string.
  • This method works like a JavaScript catch{} block for catching errors.
  • The errorCallback() is unique to Lightning Web Components. Implement it to create an error boundary component that captures errors in all the descendent components in its tree. It captures errors that occur in the descendant's lifecycle hooks or during an event handler declared in an HTML template. errorCallback() catches errors that occurs in the descendant components but not itself. You can code the error boundary component to log stack information and render an alternative view to tell users what happened and what to do next
import { LightningElement } from "lwc";
export default class ErrorCallbackExample extends LightningElement {
  error;
  stack;
  errorCallback(error, stack) {
    this.error = error;
  }
}

Hope this will help!!

12 comments:

  1. It was very Nice. This is a great blog I have read.
    #zoopersolutions
    Digital Marketing Agency.

    ReplyDelete
  2. Delhi, India's bustling capital, boasts a cadre of renowned legal practitioners who navigate its complex legal landscape with finesse. From high-profile litigators to seasoned advocates, these famous lawyers in Delhi command respect for their expertise, integrity, and dedication to justice. With a wealth of experience across diverse legal domains including civil, criminal, corporate, and constitutional law, they provide invaluable counsel and representation to clients seeking resolution in the nation's courts. Their track record of success and unwavering commitment to upholding the rule of law have earned them recognition as pillars of the legal community in Delhi.

    ReplyDelete
  3. It was very Nice. This is a great blog I have read.
    click here for ,more information

    ReplyDelete
  4. I really loved your blog post, it was so informative and I learned so much from you .
    Thanks for sharing valuable information with us
    Best Battery Pack Modelling - Autocad Cadd Course in Chennai

    ReplyDelete
  5. Looking for a reliable kraft paper burger box supplier? We offer high quality kraft paper burger boxes at best prices.
    Are you in search of high-quality Kraft boxes suppliers in Dubai? Look no further than Yashtech! With our expertise and commitment to excellence, we provide the finest Kraft boxes that meet all your packaging needs. Whether you're a small business or a large corporation, our customizable solutions are designed to impress. In this blog post, we will explore the benefits of Kraft boxes and how Yashtech can help elevate your brand. Get ready to discover the perfect packaging solution that combines functionality and aesthetics seamlessly. Let's dive in!

    Kraft boxes Dubai

    ReplyDelete
  6. Hi, I really loved your content, the way you share your content feels valuables for other. Are you interested in technology, if yes, I would like to share the content with you related to technology.

    Our company Faytech offers wide range of electronic items across various countries, though it has its roots in Germany.The reference list of well-known brands using faytech Touchscreen Displays and PCs is substantial. For example, faytech’s products are in use by business units of Bechtle, Continental, Honeywell, Unilever, Bosch, Komatsu, Qualcomm and many more.

    faytech’s Touchscreen Displays and PCs are used in a wide variety of applications. Customers use the faytech technology for home or building automation and media center applications, factories use the displays for controlling their machines and retail stores & restaurants use the Touchscreen systems to make their sales processes more efficient.
    If you really want to know more about our company, visit the website mentioned below to gain insights about technology.
    Website link- https://www.faytech.com/

    ReplyDelete
  7. Hi, I really loved your content, the way you share your content feels valuables for other. Are you interested in technology, if yes, I would like to share the content with you related to technology.

    Ample provides top-notch computer device management and comprehensive computing solutions to elevate your business operations. Our services cover end-user devices, servers, and storage, ensuring optimal performance and efficiency. Partner with us to enhance your IT infrastructure and drive success. For more details please visit: https://ample.co.in/computer/

    ReplyDelete
  8. Thanks for sharing this!
    www.samantapp.com Hire interpreter Interpreter services Book an interpreter On-demand interpreter 24/7 interpreter service Professional interpreter Online interpreter booking Video call interpreter Language interpreter for hire Certified interpreter Real-time interpreter Live interpreter service Remote interpreter Affordable interpreter services Instant interpreter booking Hire government interpreter Public sector interpreter services Interpreter for government meetings Interpreter for official government use 24/7 government interpreter support Interpreter for government agencies Language support for public sector Legal and administrative interpreter Medical interpreter service Healthcare interpreter platform Interpreter for hospitals Medical translation services 24/7 healthcare interpreter Interpreter for patient communication Interpreter for medical appointments Language support for healthcare Interpreter for medical emergencies Hospitality interpreter service Interpreter for hotels Interpreter for tourism industry Interpreter for travel agencies 24/7 hospitality interpreter support Interpreter for guest services Language support for tourism Interpreter for hospitality events Multilingual support for hotels Business interpreter service Corporate interpreter platform Interpreter for business meetings Corporate translation services 24/7 business interpreter Interpreter for corporate events Language support for businesses Interpreter for international business Interpreter for corporate training Hire medical interpreter online Book legal interpreter 24/7 On-demand business interpreter services Find certified interpreter near me Video call interpreter for hospitals Affordable interpreter for conferences Remote interpreter for government meetings Professional interpreter for corporate events Live interpreter for healthcare appointments Multilingual interpreter for travel and tourism.

    ReplyDelete
  9. Hello, I truly like your content and the way you shared it made it seem valuable to others.
    Do you have an interest in Digital Marketing? If so, I'd like to share some stuff with you.

    Optimize your business with Nuevos Techq Solutions—a dynamic IT partner in New Jersey, driving innovation and collaboration for a brighter future.
    https://nuevostech.com/

    ReplyDelete