To demonstrate the lifecycle hooks flow in Lightning Web Components (LWC) in sequence, we can create a component that logs the execution of each lifecycle hook. I'll also use getters, setters, the constructor, connected callback, render and rendered callback for this demonstration. Here's how you can implement this:
Explanation:
More about Getters and Setters:
Getters:
A getter is like a way to get or read the value of a property. Whenever you try to access a property, the getter is automatically called. Think of a getter like opening a box to look at what's inside. You can’t change the contents of the box directly through a getter — it only lets you see the current value.
Setters:
A setter is like a guardian for a property. It allows you to set or update the value of the property. Whenever you assign a new value to a property, the setter is triggered. Setters make sure that the value you’re trying to assign is allowed, and can even adjust it before it's saved. You can think of a setter as a person who checks the box and only lets in the values that meet certain rules.
Template File:
<template>
<h1>{fetchName}</h1>
<button onclick={handleChangeName}>Change Name</button>
</template>
Javascript File:
import { LightningElement } from 'lwc';
export default class LifecycleHooksDemo extends LightningElement {
// Property with getter and setter
fullName = 'LWC Lifecycle';
get fetchName() {
console.log('Getter: name is being accessed');
return this.fullName;
}
// Setter for the name property
set fetchName(value) {
console.log('Setter: name is being set to', value);
this.fullName = value;
}
handleChangeName() {
this.fetchName = 'New Name';
}
// Constructor (executed when the component is created)
constructor() {
super();
console.log('Constructor: Component is created');
}
// connectedCallback (executed when the component is inserted into the DOM)
connectedCallback() {
console.log('connectedCallback: Component is inserted into the DOM');
}
// disconnectedCallback (executed when the component is removed from the DOM)
disconnectedCallback() {
console.log('disconnectedCallback: Component is removed from the DOM');
}
// render (executed before the component is rendered to the DOM)
render() {
console.log('render: Component is about to render');
return super.render();
}
// renderedCallback (executed after the component is rendered to the DOM)
renderedCallback() {
console.log('renderedCallback: Component has been rendered');
}
}
When component is previewed:
When we click Change Name button:
No comments:
Post a Comment