Lifecycle Hooks in LWC

Saurabh Samir
5 min readOct 18, 2023

Lifecycle hooks are a fundamental aspect of any Lightning Web Component (LWC) development journey. They provide developers with the ability to control and respond to the various stages in a component’s lifecycle, allowing for a more efficient and fine-tuned approach to building web components in the Salesforce ecosystem.

In this blog, we delve into the world of LWC lifecycle hooks. We will explore what these hooks are, why they are essential, and how to use them effectively to create dynamic and responsive components. Whether you’re just starting your journey with LWC or looking to sharpen your skills, understanding these hooks is crucial for crafting powerful and efficient Lightning Web Components.

Throughout this blog, we’ll break down the different lifecycle hooks available in LWC, discuss their specific use cases, and provide practical examples to help you grasp their real-world applications. By the end of this journey, you’ll be equipped with the knowledge to harness the full potential of LWC by mastering the art of managing component lifecycles.

Lifecycle Hooks in LWC: Managing the Journey of a Lightning Web Component

Lightning Web Components (LWC) are the building blocks of dynamic and interactive user interfaces within the Salesforce platform. To truly harness their potential, developers need to understand the intricate stages that these components go through during their lifecycle. Enter the world of “Lifecycle Hooks.”

What Are Lifecycle Hooks?

Lifecycle hooks in LWC are predefined methods that allow developers to intervene at different stages of a component’s journey. These hooks provide you with the power to control, optimize, and respond to specific events and transitions in your component’s lifecycle. Understanding and using them effectively is key to creating robust and responsive components.

Here’s a brief overview of some essential lifecycle hooks:

  1. constructor(): This is where the component is initialized. You can set default values and perform one-time setup.
  2. connectedCallback(): After the component is added to the DOM, this hook runs. It’s a great place to perform DOM manipulations and data retrieval.
  3. renderedCallback(): This hook is triggered after rendering occurs. It’s ideal for operations that require knowledge of the rendered DOM.
  4. disconnectedCallback(): When the component is removed from the DOM, this hook is invoked. Use it for cleanup operations and resource releases.
  5. errorCallback(): If an error occurs during rendering, this hook is called. It’s your opportunity to gracefully handle errors.

Flow of Lifecycle hooks

First it called parent constructor then parent connectedCallBack and then if there is any child component then it moves to child constructor → connectedCall Back → renderedCallBack then it moves to parent renderedCallback

1. Creation:

  • `constructor()`: This is the first hook to run when an instance of the component is created. It’s where you initialize variables and set default values.

MIND IT !

constructor()

  1. Invoked when the instance of the component is created (similar to init() in aura).
  2. Fired in the parent component first since it flows from parent to child.
  3. You have to call super() inside first to call parent class constructor ie. LightningElement.
  4. Access element in the component template, use this.template.
import { LightningElement } from 'lwc';

export default class LifeCycleHookParent extends LightningElement {
constructor() {
super(); // call LightningElement class constructor console.log('Parent Constructor Called');
let con = this.template //access host element
console.log(con);
}
}

2. Initialization:

  • `connectedCallback()`: After the component is initialized, this hook is called. It’s an ideal place for DOM manipulations and data retrieval.

MIND IT !

connectedCallback()

  1. Invoke when component inserted into DOM.
  2. It flows Parent to Child.
  3. Used for to perform initialisation task such as fetch data, set up cache, listen events.
  4. To check component is connected in DOM, use isConnected method.
connectedCallback(){
console.log('Parent Connected Call Back called');
let cb = this.template
console.log('is connected=> ' + cb.isConnected);
}

3. Rendering:

  • `renderedCallback()`: This hook is triggered after the component’s initial render. It’s suitable for actions that require knowledge of the rendered DOM, like interacting with elements.

MIND IT !

renderedCallback()

  1. Use it to perform logic after a component has finished the rendering phase. It invoked when a component is completely rendered on UI.
  2. Flows from child to parent component.
  3. Component rendered many times during there lifecycle, to track renderedCallBack(), use isRendered boolean field.
  4. Property leads to infinite loop in renderedCallBack().
import { LightningElement } from 'lwc';
export default class LifeCycleHookParent extends LightningElement {
isRendered = true // to check component is rendered
renderedCallback() {
if (this.isRendered) {
console.log('Parent Rendered call Back called');
this.isRendered = false
}
?
}

4. Reactivity:

  • Whenever a property or variable changes in the component, it may trigger a reactivity cycle. During this cycle, the component checks for changes in properties, and if changes are detected, it re-renders and invokes the `renderedCallback` again.

5. Destruction:

  • `disconnectedCallback()`: When the component is removed from the DOM, this hook is called. It’s an excellent place for cleanup operations and releasing resources like event listeners.

MIND IT !

disconnectedCallback()

  1. Called when the element is removed from a document (remove event listener, remove time interval etc).
  2. Follows Parent to Child.
  3. Use disconnectedCallback() to clean up work done in the connectedCallback(), like removing event listeners.
  4. You can also use this hook to unsubscribe message channel.

6. Error Handling:

  • `errorCallback()`: If an error occurs during rendering, this hook is invoked. It provides an opportunity to gracefully handle errors and display appropriate messages.

MIND IT !

errorCallback()

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.

  1. Called when a descendant(Child) component throws an error.
  2. Two arguments are passed in errorCallback(error,stack), the error argument is a JavaScript native error object, and the stack argument is a string.
//Child Component
connectedCallback(){
console.log('Child Connected Call Back called');
throw new Error('problem in child component connectedCallback')
}
//Parent component
errorCallback(error, stack){
console.log(error message);
console.log('Stack: - ' + stack);
}

Understanding this flow and the use of each hook is crucial for effectively managing and optimizing the lifecycle of your LWCs. It enables you to create responsive, efficient, and interactive web components in the Salesforce ecosystem.

Why Are Lifecycle Hooks Important?

Lifecycle hooks offer several advantages:

  • Optimization: By intervening at the right time, you can optimize component rendering, improving performance and responsiveness.
  • Interactivity: You can build interactive components by responding to user actions at the right lifecycle stage.
  • Resource Management: Lifecycle hooks enable efficient resource management, like releasing event listeners and clearing timers when a component is no longer needed.

Example: A Practical Use Case

Let’s consider a simple example to illustrate the importance of lifecycle hooks. Imagine you’re building a countdown timer component. Here’s how you might use lifecycle hooks:

export default class CountdownTimer extends LightningElement {
seconds = 10;

connectedCallback() {
this.timer = setInterval(() => {
if (this.seconds > 0) {
this.seconds--;
}
}, 1000);
}

renderedCallback() {
if (this.seconds === 0) {
clearInterval(this.timer);
}
}

disconnectedCallback() {
clearInterval(this.timer);
}
}

In this example, the `connectedCallback` sets up a timer, the `renderedCallback` updates the UI when the timer reaches 0, and the `disconnectedCallback` ensures that the timer is stopped when the component is removed.

For More briefly visit the link below:

Thanks for reading ☺️

--

--

Saurabh Samir

Engineer @Accenture | Salesforce Developer | Full Stack Developer