Lifecycle Hooks
Running code at specific points in a component's life — mounting, updating, and unmounting — with onMounted and friends.
2 menit membaca
A component goes through a lifecycle: it's created, its template is mounted to the DOM, it updates in response to reactive changes, and eventually it's unmounted and removed. Lifecycle hooks let you run code at specific points in that sequence — useful for anything that needs to interact with the DOM directly, fetch initial data, or clean up after itself.
onMounted: the most common one
<script setup>
import { ref, onMounted } from "vue";
const users = ref([]);
onMounted(async () => {
const response = await fetch("/api/users");
users.value = await response.json();
});
</script>
<template>
<ul>
<li v-for="user in users" :key="user.id">{{ user.name }}</li>
</ul>
</template>onMounted runs once, after the component's template has been rendered into the real DOM for the first time. Fetching initial data here (rather than at the top level of <script setup>) matters mostly when the fetch depends on a DOM element existing, or when you specifically want the component to render an initial "loading" state before the data arrives.
onUnmounted: cleaning up
Anything a component sets up that outlives a normal render — a timer, a subscription, a manually-attached event listener — needs to be torn down when the component goes away, or it keeps running against a component that no longer exists.
<script setup>
import { ref, onMounted, onUnmounted } from "vue";
const seconds = ref(0);
let intervalId;
onMounted(() => {
intervalId = setInterval(() => {
seconds.value++;
}, 1000);
});
onUnmounted(() => {
clearInterval(intervalId);
});
</script>
<template>
<p>{{ seconds }}s elapsed</p>
</template>Without onUnmounted clearing the interval, this timer would keep firing and incrementing a ref that no component is even displaying anymore — a small but classic memory leak that compounds fast if the component mounts and unmounts repeatedly (say, a modal opened and closed many times over a session).
Other commonly used hooks
<script setup>
import { onBeforeMount, onUpdated, onBeforeUnmount } from "vue";
onBeforeMount(() => {
console.log("About to mount — DOM not available yet");
});
onUpdated(() => {
console.log("DOM updated after a reactive change");
});
onBeforeUnmount(() => {
console.log("About to unmount — DOM still available");
});
</script>onUpdated is worth a specific warning: it fires after any reactive state used in the template changes, however small, so putting expensive work in it can quietly turn cheap updates into slow ones. Most components never need it — a watch() targeting the specific value you actually care about is usually clearer and cheaper.
Why hooks are functions, not object options
In the Options API, these are lifecycle methods (mounted() {}, unmounted() {}) baked into the component object. In the Composition API, they're functions you import and call — which means you can call onMounted multiple times in one component (each callback runs independently), and more importantly, you can package "set something up on mount, tear it down on unmount" logic into a reusable composable function that any component can call, without copying the same two hooks into every file that needs it.