NexBlazers Logo
NexBlazers Learn • Build • Grow
Architecture & Apex

From Constructor to Cleanup: How LWC Lifecycle Hooks Really Fire

Written by NexBlazers Architecture Team November 28, 2026 9 min read Interactive
The basics

What are LWC lifecycle hooks?

Lightning Web Components (LWC) is Salesforce's framework for building user interface components with standard HTML and JavaScript. Every component is created, added to the page, rendered (often more than once) and eventually removed. Lifecycle hooks are methods the framework calls at each of those moments, such as connectedCallback() when the component is added and renderedCallback() after it renders. Putting code in the right hook decides whether it finds the data and page elements it expects.

A chart draws twice. A querySelector returns null on the first load but works on the second. A resize listener keeps firing after the user has left the page. Most "random" Lightning Web Component bugs are lifecycle bugs: code running in a hook before the thing it needs exists, or running again when you assumed it would run once.

In this post you'll run the lifecycle. Mount a parent and child component, re-render it, reorder it, crash the child and remove it, and watch exactly which hooks fire and in which order. Then sort real tasks into the right hook and test yourself with a quiz.

Create
constructor()
Connect
connectedCallback()
Render
renderedCallback()
Clean up & recover
disconnected / errorCallback()
Try it

The Lifecycle Simulator

Pick a scenario, then press Run or Step. Click any step to read what happens there.

Scenario

<c-account-panel>
Parent
Not created
<c-contact-tile>
Child, gets @api contact
Not created

Ready.

    Step detail

    Press Run or click a step.

    Console (simplified)
    // waiting…

    1. Parent first in, child first done

    When a parent with a child mounts, the order is: parent constructor(), parent's public properties set, parent inserted and its connectedCallback() runs, parent renders, and only then does the same sequence start for the child. The constructor, connectedCallback() and disconnectedCallback() flow from parent to child. renderedCallback() flows the other way, from child to parent. So by the time the parent's renderedCallback() runs, its children have already rendered. The full sequence is in the Lifecycle Hooks page of the LWC Developer Guide.

    2. constructor: the component exists, nothing else does

    The constructor runs when the component instance is created. Public properties aren't set yet: they're assigned after construction and before connectedCallback(). Child elements don't exist either. The rules come from the custom elements spec: call super() with no arguments as the first statement, don't return anything (a bare early return is allowed), don't use document.write() or document.open(), don't inspect attributes, children or public properties, and don't add attributes to the host element.

    import { LightningElement, api } from 'lwc';

    export default class ContactTile extends LightningElement {
      @api contact;
      isExpanded = false; // a class field is usually all the "constructor" you need

      constructor() {
        super(); // always first
        console.log(this.contact); // undefined: public properties aren't set yet
      }
    }

    3. connectedCallback: properties yes, children no

    By the time connectedCallback() runs, your @api values are in place, so it's the place to start work that depends on them: load data imperatively, subscribe to a message channel, or register a listener. The template hasn't rendered yet, so this.template.querySelector() finds nothing on the first connection. You can work with the host element itself, for example this.classList.add('is-ready'), and check this.isConnected. If you're coming from Aura, the work you did in an init handler usually moves here.

    The catch: connectedCallback() can fire more than once, for example when a list of components is reordered. If something must happen once, guard it, and pair every subscription with cleanup in disconnectedCallback().

    handleResize = () => { this.isNarrow = window.innerWidth < 600; };

    connectedCallback() {
      window.addEventListener('resize', this.handleResize);
    }

    disconnectedCallback() {
      // Listeners on window or document aren't removed for you
      window.removeEventListener('resize', this.handleResize);
    }

    4. renderedCallback: after every render, so guard it

    renderedCallback() is where the DOM exists. It's the right hook for work that needs real elements, such as starting a third-party chart library on a <canvas>. But it runs after every render, not just the first, and a component usually renders many times. One-time setup needs a flag. Changing a reactive property the template uses inside this hook schedules another render, which calls the hook again: an easy way to build an infinite loop.

    chartInitialized = false;

    renderedCallback() {
      if (this.chartInitialized) return; // runs on every render without this
      this.chartInitialized = true;
      const canvas = this.template.querySelector('canvas');
      this.chart = new window.Chart(canvas.getContext('2d'), this.config);
    }

    Don't reach for setTimeout() to "wait for the DOM" either. Salesforce's runtime anti-patterns article calls it unreliable. renderedCallback() is the signal that rendering finished.

    5. disconnectedCallback: clean up what you started

    When a component is removed, the parent's disconnectedCallback() runs, then each child's. Undo anything that outlives the component: listeners on window or document, message channel subscriptions, intervals. The browser does garbage-collect listeners on the component's own elements, but relying on garbage collection can lead to memory leaks, and on a long-lived Lightning page those add up.

    6. errorCallback: a boundary, not a try/catch

    Add errorCallback(error, stack) to a component and it becomes an error boundary for its descendants. It's called when a child throws in one of its lifecycle hooks: the constructor, connectedCallback(), render() or renderedCallback(). It doesn't catch the boundary's own errors, click handlers or async code outside the lifecycle. Render a fallback with lwc:if; without one, the framework unmounts the failing part during the re-render.

    // accountPanel.js
    error;
    errorCallback(error, stack) {
      this.error = error; // the template switches to the fallback
    }

    <!-- accountPanel.html -->
    <template lwc:if={error}><p>This section couldn't load.</p></template>
    <template lwc:else><c-contact-tile contact={contact}></c-contact-tile></template>
    Architecture Note: render() isn't technically a lifecycle hook. It's a protected method you override to choose which template to show, and it may be called before or after connectedCallback(). Keep it to returning a template and put real logic in the hooks. In Jest tests, appending the component to document.body is what fires connectedCallback() and renderedCallback(), so attach it to the document before you assert on lifecycle behaviour.
    Mini game

    Where Does This Code Go?

    Seven real tasks. Pick the hook each one belongs in.

    0 right
    Interview-ready

    Predict the Outcome

    Five scenarios that come up in real components and real interviews.

    Question 1 of 5 Score: 0

    Cheat sheet: which hook, when

    HookRunsUse it forWatch out
    constructor()Once, parent → childRarely needed; private defaultssuper() first; no @api values, children or host attributes
    connectedCallback()On insert, parent → child; can repeatLoad data, subscribe, add listenersTemplate not rendered; guard one-time work
    renderedCallback()After every render, child → parentDOM work, third-party librariesGuard with a flag; don't change reactive state
    disconnectedCallback()On removal, parent → childRemove listeners, unsubscribe, clear timersAnything on window/document is yours to remove
    errorCallback()When a descendant's hook throwsFallback UI, loggingNot its own errors, click handlers or async code

    Based on the Lifecycle Hooks section of the LWC Developer Guide and the open-source LWC lifecycle guide. The older synthetic custom element lifecycle is deprecated, so don't rely on hooks firing for a component that isn't attached to the document.

    Keep learning

    Official Resources

    Straight from Salesforce: the docs this article is based on.

    Components rendering twice or leaking listeners?

    Book a session to walk through your LWC lifecycle and performance with a practitioner.

    Book an LWC Review

    All information in this article was collected from publicly available resources, including official Salesforce documentation.