Skip to content

Lifecycle

The lifecycle option lets you run code at key points in a component’s lifecycle.

lifecycle.mount runs once when the component is mounted.

lifecycle: {
mount() {
console.log("Mounted");
},
}

This is a good place for:

  • starting timers
  • registering observers
  • connecting third-party integrations
  • performing one-time setup logic
  • injecting generated DOM elements
  • deriving state defaults at startup

lifecycle.unmount runs once when the component is disposed or unmounted.

lifecycle: {
unmount() {
console.log("Cleaned up");
},
}

This is a good place for:

  • stopping timers
  • disconnecting observers
  • general teardown logic
  • disconnecting from third-party integrations
  • removing generated DOM elements

This example shows lifecycle methods being used for markup setup and teardown.

  • When the component mounts, it appends a generated element.
  • When the component unmounts, it removes that generated markup.
const HelperMessage = defineComponent({
name: 'HelperMessage',
elements: {
message: { create: 'p' },
},
lifecycle: {
mount() {
this.root.append(this.elements.message);
},
unmount() {
this.elements.message.remove();
},
},
render: {
message() {
return {
text: 'Use arrow keys to navigate.',
};
},
},
});

Think of lifecycle as a series of checkpoints in the life of a component. Each lifecycle method gives you a predictable place to respond to those moments.