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)
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 fetchCode explanation:
setup/<script setup>runs before mount—no guaranteed DOM yet- Prefer
onMountedfor DOM access—notsetupalone
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:
<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:
onBeforeUnmount(() => {
saveDraftToSession();
});Options API Mapping
| Composition API | Options API |
|---|---|
onBeforeMount | beforeMount |
onMounted | mounted |
onBeforeUpdate | beforeUpdate |
onUpdated | updated |
onBeforeUnmount | beforeUnmount |
onUnmounted | unmounted |
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
| Avoid | Prefer |
|---|---|
Heavy logic in onUpdated | watch, computed |
Sync fetch in setup without handling loading | onMounted + loading ref |
| Skip cleanup | onUnmounted pairs onMounted |
Practice Exercise
ClockWidget.vue:
onMounted: startsetIntervalupdating time every secondonUnmounted: clear interval- 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 useFetch—SSR 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.