What are Lifecycle Hooks in Salesforce LWC?

Lightning Web Components (LWC) offer a powerful way to build modern, reactive applications on the Salesforce platform. But to fully understand the flow and master LWC, first we need to understanding the lifecycle hooks. These lifecycle hooks let us step in at important moments of a component’s life from when it’s created to when it’s removed. In this blog we will understand all concepts of LWC lifecycle hooks and where and when to use it.

What are Lifecycle Hooks?

Lifecycle hooks are special methods that Salesforce calls at specific points of a component’s existence — such as when it’s created, inserted into the DOM, rendered, or removed. These hooks help you perform actions like data initialization, DOM manipulation, event listener setup, and clean-up. In simple words Lifecycle Hooks refers to the series of phases or events that occur from the moment the component is created until is removed from DOM.

What are the different lifecycle hooks in Salesforce which we should know:

  • Constructor()
  • connectedCallback()
  • renderedCallback()
  • disconnectedCallback()
  • errorCallback(error, stack)

Order of Execution

Here is the flow how these hooks are execute in sequence:

  1. Constructor()
  2. ConnectedCallback()
  3. RenderedCallback() (may be called multiple times)
  4. DisconnectedCallback()
  5. ErrorCallback(error, stack)

Let’s Understand each lifecycle hooks and understand its purpose:

1. Constructor():

The constructor is a special JavaScript method that runs automatically when a component instance is created. In LWC, it’s the first lifecycle hook that executes before the component is added to the DOM.

Why is it Important?

The constructor is crucial because it sets up your component’s initial state before anything is rendered. It ensures default values are in place, event handlers are bound, and the component is ready for the rest of the lifecycle. All while keeping initialization clean and predictable. It will be used for:

  • Initialize variables
  • Bind methods
  • Create objects/arrays for later use

Syntax

import { LightningElement } from 'lwc';
export default class MyComponent extends LightningElement {
    constructor() {
        // Always first
        super();
        console.log('Constructor called');
        this.greeting = 'Hello LWC!';
        this.items = [];

    }
}

Limitation:

  • Cannot access the DOM.
  • Cannot access reactive properties like @api @track.
  • Cannot call Apex.

Real Life Example: Imagine opening a restaurant for the day. Before customers arrive, you set the tables, stock the kitchen, and assign staff to roles. This prep work ensures everything runs smoothly when service begins.
In the same way, the constructor in LWC sets up the component’s essentials — variables, empty data structures, and event bindings — before it’s displayed to the user.

2. connectedCallback():

It’s a lifecycle hook in Lightning Web Components that runs after the component is inserted into the DOM. connectedCallback() is like the “grand opening” of your component it is where you prepare the real content and hook it into the system before users see it.

Why is it important:

It’s important because this is the first point in the lifecycle where your component is actually in the DOM and ready to interact with data and services. It is Ideal for :

  • Calling Apex methods
  • Subscribing to events or fetching data from the server (Apex calls, HTTP requests)
  • Reading or modifying @api properties.

Syntax:

import { LightningElement } from 'lwc';

export default class MyComponent extends LightningElement {
    connectedCallback() {
        console.log('Component inserted into the DOM');
        this.loadData();
    }

    loadData() {
        // Example server call or initialization logic
    }
}

Limitation:

  • DOM is present but rendering is not completed.
  • Cannot use DOM manipulation yet.

Real Life Example: Imagine hosting a conference. The constructor is when you book the venue and prepare the schedule (setup before people arrive). connectedCallback() is when the doors open, the guests are inside, and you can start checking tickets, handing out welcome kits, and making announcements.

3. renderCallback():

It’s a lifecycle hook in Lightning Web Components that runs after every render of the component’s template. This includes the first render and any subsequent re-renders caused by reactive property changes.

Why is it important: This hook is ideal for:

  • Accessing and manipulating DOM elements inside the component.
  • Integrating with third-party libraries that require DOM access.
  • Performing UI-related adjustments after rendering.

Syntax:

import { LightningElement } from 'lwc';
export default class MyComponent extends LightningElement {
    renderedCallback() {
        console.log('Rendered callback called');
        const button = this.template.querySelector('button');
        if (button) {
            button.style.backgroundColor = 'red';
        }
    }
}

Limitation:

  • Can be called multiple times.
  • Risk of infinite loop if state is changed inside this hook.

Real Life Example: Imagine we are decorating a wedding hall. The constructor is when we book the venue and arrange the furniture layout. connectedCallback() is when we bring in flowers, food, and lighting equipment. renderedCallback() is when all the decorations are in place, and we do the final touches — like adjusting the tablecloth, placing name cards, or fixing a flower arrangement.

4. disconnectedCallback():

It’s a lifecycle hook in Lightning Web Components that runs when the component is removed from the DOM. Think of it as the “cleanup” stage of the component’s lifecycle.

Why is it Important: It’s essential for:

  • Resetting state if the component is reused later
  • Cleaning up resources (timers, intervals, subscriptions, event listeners)
  • Avoiding memory leaks
  • Cancelling in-progress operations (like Apex calls, promises, or WebSocket connections)

Syntax:

import { LightningElement } from 'lwc';
export default class MyComponent extends LightningElement {
    connectedCallback() {
        this.timerId = setInterval(() => {
            console.log('Timer running...');
        }, 1000);
    }
    disconnectedCallback() {
        clearInterval(this.timerId); // Cleanup timer
        console.log('Component removed from DOM');
    }
}

Limitation: Can’t access the DOM or do long operation.

Real life Example: Imagine you’re running a food stall at a fair. When the fair ends (component is removed from DOM), you don’t just walk away — you pack up the food, turn off the stove, take down the banner, and return borrowed equipment. This clean up ensures you’re not wasting resources, paying extra costs, or leaving a mess behind.

5. errorCallback():

It’s a last lifecycle hook in Lightning Web Components that is triggered when an error occurs in one of the child components. It is part of Salesforce’s error handling mechanism. This hook allows the parent component to gracefully handle errors from its children instead of letting them break the whole app. errorCallback() isn’t part of the regular create → render → destroy sequence. It’s a special event-driven hook that fires only when a child throws an unhandled error.

Why is it important:

  • Prevents an error in a child component from breaking the entire UI.
  • Lets you log errors, show user-friendly messages, or send details to a monitoring system.
  • Helps in debugging by giving you error context and stack trace.

Syntax:

import { LightningElement } from 'lwc';
export default class ParentComponent extends LightningElement {
    errorCallback(error, stack) {
        console.error('Error from child:', error); //The actual error object (can inspect message, name, etc.)
        console.error('Stack trace:', stack); //// Stack trace as a string showing where the error occurred
        // Show friendly error message
        this.dispatchEvent(
            new ShowToastEvent({
                title: 'Error',
                message: 'Something went wrong in a child component.',
                variant: 'error'
            })
        );
    }
}

Limitation: Only works for child error, not for parent component.

Real Life Example: Imagine of our LWC parent component as a restaurant manager, and our child components as chefs working in the kitchen. Each chef is responsible for preparing their own dish. If one chef makes a mistake say, burns the pasta or drops a plate manager will not shut down the restaurant instead of that he will complaint-handling procedure (errorCallback()):

1. Gets notified of the problem (error object).

2. Checks the report of what went wrong and where (stack trace).

3. Apologizes to the customer (shows a friendly error message).

Best Practices

  • Keep logic easy and minimal in hooks
  • Try to ignore API calls in constructor()
  • Always make sure you are using flags to avoid re-running logic in renderedCallback()
  • Always clean up intervals, listeners, or subscriptions by calling disconnectedCallback()

Common Mistakes

  • Accessing DOM in constructor.
  • If we Skip super() while creating constructor JavaScript will throw an error:
  • Forgetting cleanup in disconnectedCallback
  • Putting heavy logic in renderedCallback without conditional checks

Conclusion

Lifecycle hooks are powerful tools that give you control over a component’s behaviour. By mastering these hooks, you can build more efficient, predictable, and stable Lightning Web Components.

Understanding when and how to use each hook is key to writing production-grade LWC code. Keep experimenting and happy coding!

If you want to know more about LWC please click here.

Are you preparing for next job ? check the latest Interview Question here. Happy reading 🙂

Author

  • Aditya Kundu

    Aditya Kundu is a Salesforce professional with 4 Salesforce certifications, 2 Copado certifications, and 2 Trailhead Ranger ranks. He loves simplifying Salesforce concepts, exploring best practices, and helping others level up in their Salesforce careers and sharing knowledge and supporting the Trailblazer community.

    View all posts

Leave a Comment