By using this site, you agree to the Privacy Policy and Terms of Use.
Accept
horizontal-light horizontal-dark
  • Home
  • Tutorials
    • Salesforce AI
    • Salesforce DevOps
    • Career
    • Errors
    • Interview Questions
    • Salesforce Integration
    • Salesforce Flow
  • Salesforce Tools
  • Apex Development
  • Lightning Web Components
  • Salesforce Admin
  • About
    • Privacy Policy
    • Disclaimer
    • Terms & Conditions
    • Contact
SalesforceCornerSalesforceCorner
Search
  • Home
  • Tutorials
    • Salesforce AI
    • Salesforce DevOps
    • Career
    • Errors
    • Interview Questions
    • Salesforce Integration
    • Salesforce Flow
  • Salesforce Tools
  • Apex Development
  • Lightning Web Components
  • Salesforce Admin
  • About
    • Privacy Policy
    • Disclaimer
    • Terms & Conditions
    • Contact
Follow US
Salesforce Corner » Lightning Web Components » Salesforce LWC Lifecycle Hooks Explained with Real Examples
Lightning Web Components

Salesforce LWC Lifecycle Hooks Explained with Real Examples

Neha Panwar
By
Neha Panwar
ByNeha Panwar
Salesforce Developer and Technical Writer
Neha Panwar is a Salesforce developer and technical writer who creates practical learning resources for Salesforce administrators and developers. She specializes in Salesforce Administration, Apex, Lightning...
Follow:
- Salesforce Developer and Technical Writer
Last updated: 2026/06/21
Share
Salesforce LWC lifecycle hooks overview
SHARE

When building Lightning Web Components in Salesforce, understanding lifecycle hooks is extremely important. Lifecycle hooks help developers control what happens when a component loads, renders, updates, or gets removed from the page.

If you are starting with Lightning Web Components, lifecycle hooks are one of the first advanced concepts you should learn after understanding component creation and Salesforce project setup from VS Code Setup for Salesforce Development and Salesforce Inspector Chrome Extension Guide for Beginners

In this guide, we will understand every major Salesforce LWC lifecycle hook with simple explanations, real examples, best practices, and common mistakes.

Salesforce LWC lifecycle hooks flow diagram


Contents
What Are Lifecycle Hooks in LWC?LWC Component Lifecycle Flowconstructor() in LWCImportant RulesExampleconnectedCallback() in LWCExampleReal Example with Apexrender() in LWCExamplerenderedCallback() in LWCExampleAccessing DOM ElementsWrong ExampleCorrect ApproachdisconnectedCallback() in LWCCommon Use CasesExampleerrorCallback() in LWCExampleReal Lifecycle Execution OrderInitial LoadRe-renderComponent RemovalBest Practices for LWC Lifecycle HooksKeep constructor() SimpleUse connectedCallback() for Data LoadingAvoid Updating State in renderedCallback()Always Clean ResourcesHandle Errors GracefullyCommon Mistakes Developers MakeCalling Apex in constructor()Manipulating DOM Too EarlyInfinite Re-renderingForgetting CleanupLifecycle Hooks vs Aura Lifecycle EventsWhen Should You Use Each Lifecycle Hook?Final Thoughts

What Are Lifecycle Hooks in LWC?

Lifecycle hooks are special JavaScript callback methods automatically executed by the Lightning Web Components framework during different stages of a component’s lifecycle.

These hooks help developers:

  • Initialize components
  • Load server data
  • Access DOM elements
  • Handle rendering logic
  • Clean up resources
  • Catch runtime errors

In simple words, lifecycle hooks let you control how your component behaves from creation to destruction.

LWC Component Lifecycle Flow

A Lightning Web Component usually follows this lifecycle order:

  1. constructor()
  2. connectedCallback()
  3. render()
  4. renderedCallback()
  5. disconnectedCallback()
  6. errorCallback()

Each hook runs at a different stage.

Lightning Web Components lifecycle execution flow


constructor() in LWC

The constructor runs first when the component instance is created.

This hook is mainly used for:

  • Initializing variables
  • Setting default values
  • Binding methods

Important Rules

Inside constructor():

  • Always call super()
  • Do not access DOM elements
  • Do not call Apex methods
  • Do not access child components

Example

import { LightningElement } from 'lwc';

export default class DemoComponent extends LightningElement {

counter = 0;

constructor() {
super();

this.counter = 1;

console.log('Constructor executed');
}
}

The constructor should remain lightweight. Heavy operations here can slow component initialization.

connectedCallback() in LWC

The connectedCallback() method runs when the component is inserted into the DOM.

This is one of the most commonly used lifecycle hooks in Salesforce LWC development.

Developers usually use it for:

  • Calling Apex methods
  • Fetching data
  • Loading records
  • Setting timers
  • Subscribing to events

Apex Trigger Tutorial for Beginners in Salesforce If you are working with Apex integrations, this hook becomes very important alongside concepts explained in and SOQL Query Examples for Beginners in Salesforce (2026 Guide)

Example

import { LightningElement } from 'lwc';

export default class AccountList extends LightningElement {

connectedCallback() {
console.log('Component inserted into DOM');
}
}

Real Example with Apex

import { LightningElement } from 'lwc';
import getAccounts from '@salesforce/apex/AccountController.getAccounts';

export default class AccountData extends LightningElement {

accounts;

connectedCallback() {

getAccounts()
.then(result => {
this.accounts = result;
})
.catch(error => {
console.error(error);
});
}
}

This approach is widely used in real Salesforce projects.

render() in LWC

The render() hook helps dynamically decide which HTML template should be displayed.

Most developers do not use this hook frequently, but it becomes useful for advanced UI rendering.

Example

import { LightningElement } from 'lwc';

import desktopTemplate from './desktop.html';
import mobileTemplate from './mobile.html';

export default class ResponsiveComponent extends LightningElement {

isMobile = false;

render() {

return this.isMobile
? mobileTemplate
: desktopTemplate;
}
}

This hook is useful in responsive UI designs and enterprise applications.

renderedCallback() in LWC

The renderedCallback() method runs after the component finishes rendering on the page.

This hook is mainly used for:

  • Accessing DOM elements
  • Initializing third-party libraries
  • Performing UI calculations
  • Working with charts

Example

import { LightningElement } from 'lwc';

export default class DemoRender extends LightningElement {

renderedCallback() {

console.log('Component rendered');
}
}

Accessing DOM Elements

renderedCallback() {

const divElement =
this.template.querySelector('div');

console.log(divElement);
}

Many developers accidentally create infinite rerender loops inside renderedCallback().

Wrong Example

renderedCallback() {

this.counter++;
}

This continuously updates the component and causes performance issues.

Correct Approach

hasRendered = false;

renderedCallback() {

if(this.hasRendered) {
return;
}

this.hasRendered = true;

console.log('Run only once');
}

Performance optimization is extremely important in LWC, especially when handling large datasets or integrations like those covered in Salesforce REST API

disconnectedCallback() in LWC

The disconnectedCallback() method runs when the component is removed from the DOM.

This hook is used for cleanup operations.

Common Use Cases

  • Removing event listeners
  • Clearing timers
  • Unsubscribing platform events
  • Destroying external libraries

Example

import { LightningElement } from 'lwc';

export default class TimerComponent extends LightningElement {

intervalId;

connectedCallback() {

this.intervalId =
setInterval(() => {

console.log('Running');

}, 1000);
}

disconnectedCallback() {

clearInterval(this.intervalId);

console.log('Timer cleared');
}
}

Without proper cleanup, memory leaks can occur in enterprise applications.

errorCallback() in LWC

The errorCallback() hook catches errors from child components.

This helps create better error handling in Lightning applications.

Example

import { LightningElement } from 'lwc';

export default class ParentComponent extends LightningElement {

errorCallback(error, stack) {

console.error(error);

console.error(stack);
}
}

This hook is useful in complex component hierarchies and reusable UI frameworks.

Real Lifecycle Execution Order

Here is the actual lifecycle flow in Salesforce LWC:

Initial Load

  1. constructor()
  2. connectedCallback()
  3. render()
  4. renderedCallback()

Re-render

  1. render()
  2. renderedCallback()

Component Removal

  1. disconnectedCallback()
Salesforce LWC lifecycle hook execution order

Best Practices for LWC Lifecycle Hooks

Keep constructor() Simple

Only initialize variables inside constructor.

Use connectedCallback() for Data Loading

This is the safest place to call Apex or initialize services.

Avoid Updating State in renderedCallback()

Improper state updates can create infinite rendering loops.

Always Clean Resources

Use disconnectedCallback() to clear timers and listeners.

Handle Errors Gracefully

Use errorCallback() for better application stability.

Common Mistakes Developers Make

Calling Apex in constructor()

This is not recommended because the component is not fully initialized.

Manipulating DOM Too Early

DOM elements are not available in constructor() or connectedCallback().

Infinite Re-rendering

Updating tracked properties inside renderedCallback() causes loops.

Forgetting Cleanup

Not clearing intervals or listeners can impact performance.

Lifecycle Hooks vs Aura Lifecycle Events

Many developers moving from Aura Components to LWC often compare lifecycle methods.

LWC lifecycle hooks are:

  • Faster
  • Cleaner
  • Standards-based
  • Easier to maintain

This is one reason Lightning Web Components are replacing Aura Components in modern Salesforce development.

When Should You Use Each Lifecycle Hook?

Lifecycle HookMain Purpose
constructor()Initialize variables
connectedCallback()Fetch data and setup
render()Dynamic template rendering
renderedCallback()Access DOM and UI logic
disconnectedCallback()Cleanup operations
errorCallback()Handle child component errors

Final Thoughts

Understanding Salesforce LWC lifecycle hooks is essential for building scalable and high-performance Lightning Web Components.

Most real-world Salesforce projects heavily rely on connectedCallback(), renderedCallback(), and disconnectedCallback() for handling UI rendering, Apex communication, and cleanup logic.

As you continue learning LWC, you should also explore advanced concepts like parent-child communication, wire adapters, and imperative Apex calls. These topics work closely with lifecycle hooks in real Salesforce applications.

For better backend understanding, you can also read:

  • Salesforce Governor Limits with Real Examples and Best Practices
  • Queueable Apex in Salesforce for Beginners: Complete Async Processing Guide
  • Batch Apex in Salesforce: Complete Guide with Real Examples
  • Apex Test Classes for Beginners in Salesforce
TAGGED:connectedCallbackdisconnectedCallbacklightning web componentsLWC Lifecycle Hookslwc tutorialrenderedCallbacksalesforce developersalesforce lwcSalesforce UI Development
Share This Article
Facebook Email Print
ByNeha Panwar
Salesforce Developer and Technical Writer
Follow:
Neha Panwar is a Salesforce developer and technical writer who creates practical learning resources for Salesforce administrators and developers. She specializes in Salesforce Administration, Apex, Lightning Web Components (LWC), Flow, integrations, and automation. Through Salesforce Corner, she publishes step-by-step tutorials, coding guides, and real-world solutions designed to help readers understand Salesforce concepts and apply them in projects with confidence.
Leave a Comment Leave a Comment

Leave a Reply Cancel reply

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

Latest Post

Salesforce approval process diagram
Salesforce Approval Process: A Practical Guide with Real Business Examples
Salesforce Admin
Salesforce relationship comparison infographic
Master-Detail or Lookup? Choosing the Right Relationship in Salesforce
Salesforce Admin
Salesforce dynamic forms interface illustration
Salesforce Dynamic Forms: A Better Way to Show and Hide Fields
Salesforce Flow
Salesforce flow debugging guide
How to Debug and Fix Salesforce Flow Errors ?
Salesforce Flow
Salesforce Flow Loops tutorial diagram
Salesforce Flow Loops: Collections, Iteration, and Best Practices
Salesforce Flow

Stay Updated with Salesforce Tutorials

Get the latest Salesforce guides, tutorials, and developer tips delivered to your inbox.
slaesforce corner mascot

Explore More Topics

  • salesforce admin
  • salesforce developer
  • Salesforce Admin
  • salesforce tutorial
  • Salesforce Development
  • salesforce automation
  • salesforce apex
  • salesforce security
  • Apex Development
  • lightning web components
  • Lightning Web Components
  • Salesforce Tutorials
  • salesforce lwc
  • Salesforce Tools
  • Salesforce Beginner Guide
horizontal-dark-transparent

Learn Salesforce development with practical tutorials, Apex guides, integration examples, and real-world solutions for developers.

  • Quick Links:
  • About
  • Contact
  • Privacy Policy
  • Disclaimer
  • Terms & Conditions
Facebook Twitter Youtube Linkedin-in

Salesforce Corner © 2026

Welcome Back!

Sign in to your account

Username or Email Address
Password

Lost your password?