Vue Lifecycle Hooks
Every component instance goes through a series of steps: it is created, mounted into the DOM, updated when its data changes, and finally unmounted when it's removed. Vue lets you run your own code at each step with lifecycle hooks. They're how you fetch data when a component appears, set up timers or third-party libraries, and clean up afterwards.
The lifecycle at a glance
| Options API | Composition API | When it runs |
|---|---|---|
beforeCreate |
— (the start of setup()) |
Instance is being initialised; no data yet |
created |
— (the body of setup()) |
Data, computed and methods are ready; no DOM yet |
beforeMount |
onBeforeMount |
Right before the first render into the DOM |
mounted |
onMounted |
The component's elements are in the DOM |
beforeUpdate |
onBeforeUpdate |
Data changed; DOM is about to be patched |
updated |
onUpdated |
DOM has been updated |
beforeUnmount |
onBeforeUnmount |
Right before removal; everything still works |
unmounted |
onUnmounted |
Removed; clean-up time |
activated / deactivated |
onActivated / onDeactivated |
Shown / hidden by <KeepAlive> |
errorCaptured |
onErrorCaptured |
An error was thrown in a descendant |
Watching the order
Mount the component, type in the input to trigger updates, then remove it. The log shows each hook as it fires.
<div id="app">
<button @click="show = !show">{{ show ? 'Unmount' : 'Mount' }} the component</button>
<life-demo v-if="show"></life-demo>
</div>
<script type="module">
import { createApp } from 'vue';
const app = createApp({ data: () => ({ show: true }) });
app.component('life-demo', {
data: () => ({ text: 'hello' }),
beforeCreate() { console.log('1. beforeCreate'); },
created() { console.log('2. created — text =', this.text, '| $el exists?', !!this.$el); },
beforeMount() { console.log('3. beforeMount'); },
mounted() { console.log('4. mounted — $el is a', this.$el.tagName); },
beforeUpdate() { console.log('5. beforeUpdate'); },
updated() { console.log('6. updated — text =', this.text); },
beforeUnmount() { console.log('7. beforeUnmount'); },
unmounted() { console.log('8. unmounted'); },
template: `<p><input v-model="text"> {{ text }}</p>`
});
app.mount('#app');
</script>onMounted and onUnmounted in setup()
In the Composition API you import hook functions and call them inside setup(). Each takes a callback. A typical job: start something when the component appears and stop it when it disappears. Forgetting the clean-up leads to memory leaks and timers that keep running after the component is gone.
<div id="app">
<label><input type="checkbox" v-model="visible"> Show stopwatch</label>
<stop-watch v-if="visible"></stop-watch>
</div>
<script type="module">
import { createApp, ref, onMounted, onUnmounted } from 'vue';
const app = createApp({ setup: () => ({ visible: ref(true) }) });
app.component('stop-watch', {
setup() {
const tenths = ref(0);
let timer = null;
onMounted(() => {
timer = setInterval(() => tenths.value++, 100);
console.log('stopwatch started');
});
onUnmounted(() => {
clearInterval(timer);
console.log('stopwatch stopped after', (tenths.value / 10).toFixed(1), 's');
});
return { tenths };
},
template: `<p style="font: 28px monospace">⏱ {{ (tenths / 10).toFixed(1) }} s</p>`
});
app.mount('#app');
</script>Where to do what
| Task | Hook |
|---|---|
| Start fetching data | created / directly in setup() (no need to wait for the DOM) |
| Read element size, focus an input, start a chart library | mounted / onMounted |
Add window / document event listeners |
add in onMounted, remove in onUnmounted |
| Stop timers, intervals, sockets, observers | onBeforeUnmount or onUnmounted |
| React to data changes | usually a watcher, not updated |
Note: Hooks must be registered synchronously during
setup(). Code likesetTimeout(() => onMounted(...))or registering a hook after anawaitwon't work, because Vue no longer knows which component is being set up.
Global listeners need clean-up
<style> .size { font: 18px monospace; padding: 10px; background: #ecfdf5; } </style>
<div id="app">
<button @click="on = !on">{{ on ? 'Remove' : 'Add' }} tracker</button>
<window-size v-if="on"></window-size>
</div>
<script type="module">
import { createApp, ref, onMounted, onBeforeUnmount } from 'vue';
const app = createApp({ setup: () => ({ on: ref(true) }) });
app.component('window-size', {
setup() {
const width = ref(window.innerWidth);
const height = ref(window.innerHeight);
const update = () => {
width.value = window.innerWidth;
height.value = window.innerHeight;
};
onMounted(() => window.addEventListener('resize', update));
onBeforeUnmount(() => {
window.removeEventListener('resize', update);
console.log('resize listener removed');
});
return { width, height };
},
template: `<div class="size">Window: {{ width }} × {{ height }} px (resize the page)</div>`
});
app.mount('#app');
</script>Parent and child order
When a parent contains children, Vue mounts children first: the parent's mounted runs only after all its children are mounted, because only then is the parent's DOM complete. Unmounting is the same: children's unmounted hooks fire before the parent's.
parent beforeMount
child beforeMount
child mounted
parent mountedTip:
setup()runs beforebeforeCreateand replaces bothbeforeCreateandcreatedin the Composition API. Code you'd put increatedsimply goes in the body ofsetup().
Test yourself
Which hook is the first one in which the component's DOM elements exist?
createdbeforeMountmountedbeforeCreate
You start a setInterval in onMounted. Where should you call clearInterval?
onBeforeMountonUnmounted(oronBeforeUnmount)onUpdated- There's no need, Vue clears it
Which is mounted first: a parent or its child?
- The parent
- The child
- Both at the same time
- It's random