Lifecycle Hooks

Introduction

Lifecycle hooks run code at specific moments—when a component mounts, updates, or unmounts. Use them to fetch data, subscribe to events, or clean up timers and listeners. In Composition API, hooks like onMounted replace Options API names like mounted.

Prerequisites

Hook Timeline (Simplified)

text
setup() / <script setup> runs

onBeforeMount

onMounted          ← DOM inserted; good for fetch, focus, charts

onUpdated          ← after reactive DOM patch (use sparingly)

onBeforeUnmount

onUnmounted        ← cleanup timers, listeners, abort fetch

Code explanation:

  • setup / <script setup> runs before mount—no guaranteed DOM yet
  • Prefer onMounted for DOM access—not setup alone

onMounted: Fetch Data

Later chapters move fetch into composables and Pinia—Fetching API.

Cleanup on onUnmounted

Missing cleanup causes memory leaks when navigating away in SPAs.

Abort Fetch on Unmount

onUpdated

Runs after DOM updates due to reactive changes:

vue
<script setup lang="ts">
import { ref, onUpdated } from "vue";
 
const count = ref(0);
 
onUpdated(() => {
  console.log("DOM updated, count is", count.value);
});
</script>

Use rarely—often watch or nextTick is clearer. Avoid infinite loops by not mutating same state unconditionally inside onUpdated.

onBeforeMount / onBeforeUnmount

onBeforeMount — last chance before DOM insert; seldom needed.

onBeforeUnmount — component still fully functional; good for teardown before DOM removal:

vue
onBeforeUnmount(() => {
  saveDraftToSession();
});

Options API Mapping

Composition APIOptions API
onBeforeMountbeforeMount
onMountedmounted
onBeforeUpdatebeforeUpdate
onUpdatedupdated
onBeforeUnmountbeforeUnmount
onUnmountedunmounted

Vue 2 beforeDestroy / destroyed → Vue 3 beforeUnmount / unmounted.

Lifecycle with keep-alive (Awareness)

<KeepAlive> caches inactive components—use onActivated / onDeactivated instead of remounting. See Vue Router docs when wrapping views.

What Not to Do in Lifecycle

AvoidPrefer
Heavy logic in onUpdatedwatch, computed
Sync fetch in setup without handling loadingonMounted + loading ref
Skip cleanuponUnmounted pairs onMounted

Practice Exercise

ClockWidget.vue:

  1. onMounted: start setInterval updating time every second
  2. onUnmounted: clear interval
  3. Display formatted time string

FAQ

setup vs onMounted for fetch?

onMounted—clearer intent; setup async with Suspense is advanced.

Multiple onMounted calls?

Allowed—they run in registration order.

Lifecycle in composables?

Call hooks inside composables—must be during setup synchronously.

SSR note?

onMounted does not run on server—fetch for SSR uses Nuxt useFetchSSR intro.

Why not created (Vue 2)?

Vue 3 setup replaces beforeCreate / created.

Timer still running after navigate?

You forgot onUnmounted cleanup—check Router navigation away from page.