onMounted
Register setup that runs when its owning app or component mounts.
Register setup that runs when its owning app or component mounts.
Overview
The onMounted function allows you to register a callback function that will be executed when an app or component is mounted or initialized. This is particularly useful for performing setup tasks or side effects when a component becomes active.
Try it live
Ready. Mount the ticker to start its interval.
Unmount the child: the tick count stops. Remount it: a fresh interval starts. The parent keeps the totals.
import { defineComponent, html, onMounted, onUnmounted, ref } from 'regor'
export function createLifecycle(interactive = false) {
const active = ref(false)
const toggle = () => active(!active())
const ticks = ref(0)
const starts = ref(0)
const cleanups = ref(0)
const lastEvent = ref('Ready. Mount the ticker to start its interval.')
const SessionTicker = defineComponent(
html`<p class="guide-ticker">
Interval running <span aria-hidden="true">●</span>
</p>`,
{
context: () => {
let timer: ReturnType<typeof setInterval> | undefined
onMounted(() => {
starts(starts() + 1)
lastEvent('onMounted → start interval')
timer = setInterval(() => ticks(ticks() + 1), 500)
})
onUnmounted(() => {
clearInterval(timer)
cleanups(cleanups() + 1)
lastEvent('onUnmounted → clear interval')
})
return {}
},
},
)
// No child is mounted during static rendering, so the build creates no timer.
return {
interactive,
active,
toggle,
ticks,
starts,
cleanups,
lastEvent,
components: { SessionTicker },
}
}
export const lifecycleTemplate = html` <div class="guide-demo">
<div class="guide-session-bar">
<button type="button" @click="toggle" :disabled="!interactive">
{{ active ? 'Unmount ticker' : 'Mount ticker' }}</button
><span>{{ active ? 'Child is mounted' : 'Child is unmounted' }}</span>
</div>
<SessionTicker r-if="active" />
<div class="guide-metrics">
<div><output>{{ ticks }}</output><span>Total ticks</span></div>
<div><output>{{ starts }}</output><span>Mounts</span></div>
<div><output>{{ cleanups }}</output><span>Cleanups</span></div>
</div>
<p class="guide-event" role="status">{{ lastEvent }}</p>
<p class="guide-hint">
Unmount the child: the tick count stops. Remount it: a fresh interval
starts. The parent keeps the totals.
</p>
</div>` import { createApp, RegorConfig, useScope } from 'regor'
import { apiExamples } from './examples'
const element = document.getElementById('api-demo')
const name = element?.dataset.example
if (element && name && Object.hasOwn(apiExamples, name)) {
const example = apiExamples[name as keyof typeof apiExamples]
const scope = useScope<object>(() => example.create(true))
const config =
'config' in scope.context && scope.context.config instanceof RegorConfig
? scope.context.config
: undefined
createApp(scope, { element, template: example.template }, config)
} Mount the child ticker, then unmount it. The parent keeps totals while the child releases its interval.
Usage
Registering the onMounted Callback
To register an onMounted callback, simply call the onMounted function and pass the desired callback function as an argument. The callback will be executed when the app or component is mounted.
import { createApp, defineComponent, html, useScope, onMounted } from 'regor'
const userRow = defineComponent(html`<div></div>`, {
context: () => {
// Register an onMounted callback
onMounted(() => {
// Perform initialization tasks
console.log('Component is mounted!')
})
return {}
},
})
createApp(
useScope(() => {
// Register an onMounted callback
onMounted(() => {
// Perform initialization tasks
console.log('App is mounted!')
})
return {}
}),
) Parameters
onMounted(required): A callback function that will be executed when the component or scope is mounted.
Pair mounted setup with unmounted cleanup when it starts timers, listeners, or subscriptions.
Notes
-
onMountedcallbacks can be useful for initializing state, fetching data, setting up event listeners, or any other task that should be performed when a component becomes active. -
Multiple
onMountedcallbacks can be registered, and they will be executed in the order they were registered. -
onMountedis often used in conjunction withonUnmountedto define cleanup tasks that should be performed when a component is unmounted.