Lifecycle Hooks
Run code at specific moments in a component's life — mounting, updating, and unmounting — using lifecycle hooks.
The Component Lifecycle
Every component goes through the same broad stages: it's created, mounted into the DOM, potentially updated many times as reactive state changes, and eventually unmounted and removed. Lifecycle hooks let you run code at each of these specific moments.
onMounted
onMounted runs once the component's DOM has been created and inserted — the right place for anything that needs the actual rendered DOM, or an initial data fetch.
<script setup>import { ref, onMounted } from 'vue';
const posts = ref([]);
onMounted(async () => { const res = await fetch('/api/posts'); posts.value = await res.json();});</script>onUpdated
onUpdated runs after the component re-renders due to a reactive data change — used far less often than onMounted, and usually only for specific DOM measurement needs.
<script setup>import { onUpdated } from 'vue';
onUpdated(() => { console.log('The DOM was just updated');});</script>onUnmounted
onUnmounted runs right before a component is removed from the DOM — the place to clean up anything the component set up, like a timer or an external event listener.
<script setup>import { onMounted, onUnmounted } from 'vue';
let intervalId;
onMounted(() => { intervalId = setInterval(() => console.log('tick'), 1000);});
onUnmounted(() => { clearInterval(intervalId); // prevent a memory leak / dangling timer});</script>Cleaning Up Side Effects
Anything started in onMounted that outlives the component — timers, WebSocket connections, manually added event listeners — needs a matching cleanup in onUnmounted, or it keeps running (and consuming memory) after the component is gone.
Common Beginner Mistakes
A fetch call directly in <script setup> runs once, at component creation — usually fine, but onMounted is the conventional, explicit place for it, especially if it depends on a mounted DOM element.
This is one of the most common sources of memory leaks in single-page applications — always pair setup with matching cleanup.
FAQs
Yes — onBeforeMount exists, though in the Composition API, code at the top level of <script setup> already runs at that equivalent point, so it's rarely needed explicitly.
Yes — unlike the Options API's single mounted() option, you can call onMounted() as many times as you like, and each callback runs in order.
Summary
Lifecycle hooks let you hook into specific moments of a component's life, with onMounted and onUnmounted covering the vast majority of real-world needs. Next, you'll learn to extract and reuse stateful logic across components with composables.