Component lifecycles
Genesis elements go through several lifecycle stages from creation to removal. Understanding these stages is crucial for properly initializing components, cleaning up and for state management.
GenesisElement
has access to a number of methods that enable you to control the lifecycle. These are described below.
Connected and disconnected methods
connectedCallback
lifecycle runs when a component is added to the DOM - this is the perfect time for set-up.
disconnectedCallback
lifecycle runs when a component is removed from the DOM - this is the perfect time for clean-up.
import {
attr,
customElement,
GenesisElement,
html,
} from "@genesislcap/web-core";
const template = html<MyButton>`<button>Click Me</button>`;
@customElement({
name: "my-button",
template,
styles,
})
export class MyButton extends GenesisElement {
@attr label: string = "Submit";
@attr disabled: boolean = false;
connectedCallback() {
super.connectedCallback(); // Let GenesisElement do its setup first
console.log("Button is now connected to the DOM and ready for interaction");
}
disconnectedCallback() {
super.disconnectedCallback(); // Let GenesisElement do its cleanup first
console.log("Button is no longer interactive and removed from DOM");
}
}
Changed callbacks
The changed callback lifecycle runs when the attributes or properties of an element are updated, in order to handle state changes. The name of the method varies, based on the name of the attribute or property.
The example below is for handling changes to the label attribute of MyButton
. So, the method used is labelChanged
. When this method is triggered, the following statement is added to the log:
<my-button label="Cancel"></my-button>
Button text changed from Submit to Cancel
import {
attr,
customElement,
GenesisElement,
html,
} from "@genesislcap/web-core";
const template = html<MyButton>`<button>Click Me</button>`;
@customElement({
name: "my-button",
template,
styles,
})
export class MyButton extends GenesisElement {
@attr label: string = "Submit";
@attr disabled: boolean = false;
labelChanged(oldValue, newValue) {
console.log(`Button text changed from ${oldValue} to ${newValue}`);
}
}
The example above does not include the connectedCallback
and disconnectedCallback
. If you want to use this snippet in your lifecycles, you need to add these methods.