onMounted, onUpdated, onUnmounted — and Friends
Lifecycle Hooks
Lifecycle hooks let you run code at specific points in a component's lifespan — from creation through mount, updates, and tear-down.
What you'll learn
- Use onMounted for setup
- Use onUnmounted for cleanup
- Know each hook (onBeforeMount, onUpdated, onActivated, etc.)
Lifecycle hooks let you tap into key moments in a component’s life: when it mounts, when it updates, when it unmounts. In the Composition API each hook is a standalone function — call it inside <script setup> to register a callback.
onMounted & onUnmounted
The two most common — run code after the DOM exists, and clean it up when the component leaves.
import { onMounted, onUnmounted } from 'vue'
let timer: number
onMounted(() => {
console.log('component is in the DOM')
timer = window.setInterval(() => console.log('tick'), 1000)
})
onUnmounted(() => {
clearInterval(timer)
}) The Full Set
import {
onBeforeMount, onMounted,
onBeforeUpdate, onUpdated,
onBeforeUnmount, onUnmounted,
onErrorCaptured,
onActivated, onDeactivated, // KeepAlive
} from 'vue'
onBeforeMount(() => console.log('about to mount'))
onMounted(() => console.log('mounted'))
onBeforeUpdate(() => console.log('about to update'))
onUpdated(() => console.log('updated'))
onBeforeUnmount(() => console.log('about to unmount'))
onUnmounted(() => console.log('gone')) Error Capture
onErrorCaptured catches errors thrown in descendants — like a React error boundary.
onErrorCaptured((err, instance, info) => {
log(err, info)
return false // stop the error from propagating up
}) KeepAlive Hooks
Inside a <KeepAlive> parent, components are cached rather than destroyed. onActivated / onDeactivated fire as the cached component is shown or hidden.
onActivated(() => refreshData())
onDeactivated(() => pausePolling()) Order of Things
setup runs first (before beforeMount). The order is: setup → beforeMount → mounted → (updates…) → beforeUnmount → unmounted.