top of page
Writer's pictureNeeraj Singh

Lifecycle Hooks and Composition in LWC


Lifecycle Hooks and Composition in LWC

In Lightning Web Components (LWC), lifecycle hooks and composition are essential tools for building dynamic and reusable components. Lifecycle hooks provide entry points to execute code at specific stages of a component's lifecycle, while the composition approach helps modularize and reuse logic effectively.

Lifecycle Hooks and Composition in LWC

Lifecycle hooks enable developers to interact with components at various stages: initialization, rendering, and destruction. Here's a breakdown of commonly Lifecycle Hooks and Composition in LWC:

1. constructor()

  • Purpose: Called when the component is created.

  • Use Case: Ideal for initializing variables.

  • Limitation: Cannot access DOM or @api properties.


constructor() {

super();

console.log("Constructor called");

}


2. connectedCallback()

  • Purpose: Called when the component is inserted into the DOM.

  • Use Case: Fetch data, subscribe to events, or manipulate the DOM.


connectedCallback() {

console.log("Component is connected to the DOM");

}


3. renderedCallback()

  • Purpose: Invoked after every render (post DOM update).

  • Use Case: Useful for DOM manipulations or post-render logic.


renderedCallback() {

console.log("Rendered callback called");

}


4. disconnectedCallback()

  • Purpose: Triggered when the component is removed from the DOM.

  • Use Case: Cleanup activities like unsubscribing from events or clearing timers.


disconnectedCallback() {

console.log("Component is disconnected from the DOM");

}


5. errorCallback(error, stack)

  • Purpose: Captures errors in the component or its children.

  • Use Case: Implement error handling and fallback UI.


errorCallback(error, stack) {

console.log("Error occurred:", error);

}


Lifecycle Hook Flow

  1. constructor()

  2. connectedCallback()

  3. render()

  4. renderedCallback()

  5. (When removed) disconnectedCallback()


    Composition in LWC

    The Composition API in LWC allows modularization by composing smaller pieces of functionality into reusable components. It emphasizes clean, maintainable, and reusable code structures.

    Key Concepts in Composition:

    1. Encapsulation Using Helper Functions

      • Delegate logic to helper modules for state management or reusable functions.

    2. Slots for Flexible Layouts

      • Slots let child components accept and display content provided by their parent components.


    <template>

    <div>

    <slot></slot> <!-- Content provided by parent -->

    </div>

    </template>


    Dynamic Components

    • Dynamically instantiate components using the createElement method.

    import { createElement } from 'lwc';

    import ChildComponent from 'c/childComponent';

    const element = createElement('c-child-component', { is: ChildComponent });

    this.appendChild(element);


    Composition via Events

    • Use custom events to enable parent-child communication.

    this.dispatchEvent(new CustomEvent('update', { detail: { value: 'Updated Data' } }));


    Example: Combining Lifecycle Hooks and Composition

    Parent Component (parentComponent.html)

    <template>

    <lightning-button label="Click Me" onclick={handleClick}></lightning-button>

    <c-child-component message={childMessage}></c-child-component>

    </template>

    Parent Component (parentComponent.js)

    import { LightningElement } from 'lwc';

    export default class ParentComponent extends LightningElement {

    childMessage = 'Message from Parent';


    handleClick() {

    this.childMessage = 'Updated Message from Parent';

    }


    connectedCallback() {

    console.log('Parent component connected');

    }

    }


    Child Component (childComponent.html)

    <template>

    <div>

    <p>{message}</p>

    </div>

    </template>


    Child Component (childComponent.js)


    import { LightningElement, api } from 'lwc';

    export default class ChildComponent extends LightningElement {

    @api message;


    connectedCallback() {

    console.log('Child component connected');

    }


    renderedCallback() {

    console.log('Child component rendered');

    }

    }


    Summary

    • Lifecycle Hooks: Manage the component lifecycle efficiently, from creation to cleanup.

    • Composition: leverages modularity to create reusable and maintainable components.

    • Integration: By combining hooks and composition, developers can build robust, scalable LWC applications.


6 views0 comments

Comments

Rated 0 out of 5 stars.
No ratings yet

Add a rating
bottom of page