Observe a component lifecycle
Run creation, patch cleanup, update and removal through one component.
Table of contents
APIs used
- mount
- Starts a Valyrian.js application on a DOM target.
- onCleanup
- Runs before each patch of the vnode subtree and before that subtree detaches.
- onCreate
- Runs when a component first enters the rendered tree and may return cleanup or a promise.
- onRemove
- Runs after the component subtree detaches from the rendered tree.
- onUpdate
- Runs after later patches while the component remains in the rendered tree and may return cleanup.
- unmount
- Ends the mounted application lifecycle.
Run this recipe
- Starting project
- Use the local TSX and ESM project from Stage 1 with Valyrian.js installed and its ESM browser build configured.
- File
- Replace src/client-entry.tsx with this recipe snippet.
- Run
- Run npm run build, serve public with npx --yes serve@14.2.5 public --listen 8000, open http://localhost:8000 and use the example's visible controls.
- Observable result
- The console records onCreate, then onCleanup before onUpdate, and finally onCleanup before onRemove.
Starting point
Create a component that records all four lifecycle hooks.
Steps
Use onCreate for initial entry, onCleanup before later patches and detach, onUpdate after a patch and onRemove after detach. Trigger a patch and finish with unmount.
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
The console records onCreate, then onCleanup before onUpdate, and finally onCleanup before onRemove.