Run work through the view lifecycle
Observe creation, patch cleanup, update and removal as one component changes and leaves the rendered tree.
The example records onCreate after the initial render, onCleanup before each later patch and detach, onUpdate after a patch and onRemove after unmount.
Table of contents
Main APIs
- onCreate
- Runs when a component first enters the rendered tree and may return cleanup or a promise.
- onUpdate
- Runs after later patches while the component remains in the rendered tree and may return cleanup.
- onCleanup
- Runs before each patch of the vnode subtree and before that subtree detaches.
- onRemove
- Runs after the component subtree detaches from the rendered tree.
tsximport {
mount,
onCleanup,
onCreate,
onRemove,
onUpdate,
unmount,
} from "valyrian.js";
let patches = 0;
const lifecycleLog: string[] = [];
const record = (hook: string) => {
lifecycleLog.push(hook);
console.log(lifecycleLog.join(" -> "));
};
const LifecycleDemo = () => {
onCreate(() => record("onCreate"));
onCleanup(() => record("onCleanup"));
onUpdate(() => record("onUpdate"));
onRemove(() => record("onRemove"));
return (
<main>
<p>Patch count: {patches}</p>
<p>Lifecycle order is written to the console.</p>
<button
type="button"
onclick={() => {
patches += 1;
}}
>
Patch component
</button>
<button
type="button"
onclick={() => {
unmount();
}}
>
Unmount component
</button>
</main>
);
};
mount("body", LifecycleDemo);Result
Patch component updates the count and records cleanup before onUpdate. Unmount component records cleanup before onRemove.