onUnmounted

Register cleanup for resources owned by an app, component, or scope.

onUnmountedLifecycle and Scope

Register cleanup for resources owned by an app, component, or scope.

Overview

The onUnmounted function allows you to register a callback function that will be executed when a component or scope is unmounted or cleaned up. This is useful for performing cleanup tasks or removing event listeners when a component becomes inactive.

Try it live

Setup and cleanup with an ownerLive API
Child is unmounted
0Total ticks
0Mounts
0Cleanups

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 onUnmounted Callback

To register an onUnmounted callback, simply call the onUnmounted function and pass the desired callback function as an argument. The callback will be executed when the component or scope is unmounted or cleaned up.

import { createApp, defineComponent, html, useScope, onUnmounted } from 'regor'

const userRow = defineComponent(html`<div></div>`, {
  context: () => {
    // Register an onUnmounted callback
    onUnmounted(() => {
      // Perform cleanup  tasks
      console.log('Component is unmounted!')
    })
    return {}
  },
})

createApp(
  useScope(() => {
    // Register an onUnmounted callback
    onUnmounted(() => {
      // Perform cleanup tasks
      console.log('App is unmounted!')
    })
    return {}
  }),
)

Parameters

  • onUnmounted (required): A callback function that will be executed when the app or component is unmounted or cleaned up.
Cleanup belongs beside setup

Keep the resource handle near the hook that releases it. The ticker preview shows its interval stopping after unmount.

Notes

  • onUnmounted callbacks can be useful for cleaning up resources, removing event listeners, or any other task that should be performed when a component becomes inactive.

  • Multiple onUnmounted callbacks can be registered, and they will be executed in the order they were registered.

  • onUnmounted is often used in conjunction with onMounted to define initialization and cleanup tasks for components or scopes.

See Also

Related APIs and guides Continue with the references connected to onUnmounted.

Back to the API list