Skip to content

Lifecycle overview

Lifecycle hooks must be registered synchronously during component setup, which means at the top level of a Macro component.

ts
import { defineHtml, onMounted, onUnmounted } from "@elfui/core";

onMounted(() => {
  console.log("mounted");
});

onUnmounted(() => {
  console.log("unmounted");
});

export const Demo = defineHtml(`<p>Demo</p>`);

Lifecycle hooks

APITiming
onBeforeMountBefore the first render is committed
onMountedAfter final DOM and template refs are ready
onBeforeUpdateBefore a reactive DOM update
onUpdatedAfter a reactive DOM update
onBeforeUnmountBefore resources and DOM are released
onUnmountedAfter the component is fully detached
onActivatedWhen a KeepAlive component becomes active
onDeactivatedWhen a KeepAlive component becomes inactive
onAttributeChangedAfter an observed host attribute changes
onErrorCapturedWhen a descendant or lifecycle operation fails

onMounted may return a cleanup callback. The cleanup runs in last-in-first-out order during unmount, after onBeforeUnmount and before component DOM and scopes are released:

ts
onMounted(() => {
  const resource = createResource();
  return () => resource.destroy();
});

A hook may return a Promise. ElfUI does not delay the mount or unmount sequence while waiting for it, but a rejection is routed through onErrorCaptured and the application errorHandler. An asynchronous onMounted may resolve to a cleanup callback; if unmount already happened, ElfUI invokes that cleanup immediately.

TIP

onAttributeChanged((name, oldValue, newValue) => {}) is intended for native attributes that are not declared as props. Prefer props and reactive bindings for the regular declared data flow.