Lifecycle hooks let you run code at important moments in a component's life, like when it starts or stops. This helps you manage tasks like fetching data or cleaning up.
0
0
Lifecycle hooks in Composition API in Vue
Introduction
When you want to run code right after a component appears on the screen.
When you need to clean up timers or event listeners before a component disappears.
When you want to react to changes in component state or props during its life.
When you want to run code before the component updates its display.
When you want to run code after the component updates its display.
Syntax
Vue
import { onMounted, onUnmounted, onUpdated, onBeforeMount, onBeforeUpdate } from 'vue'; export default { setup() { onMounted(() => { // code to run after component mounts }); onUnmounted(() => { // code to run before component unmounts }); onUpdated(() => { // code to run after component updates }); onBeforeMount(() => { // code to run before component mounts }); onBeforeUpdate(() => { // code to run before component updates }); } }
All lifecycle hooks are called inside the setup() function.
Each hook takes a function that runs at the right time.
Examples
This runs code right after the component appears on the screen.
Vue
import { onMounted } from 'vue'; export default { setup() { onMounted(() => { console.log('Component is now visible'); }); } }
This runs code just before the component disappears, useful for cleanup.
Vue
import { onUnmounted } from 'vue'; export default { setup() { onUnmounted(() => { console.log('Component is about to be removed'); }); } }
This runs code after the component updates its display.
Vue
import { onUpdated } from 'vue'; export default { setup() { onUpdated(() => { console.log('Component just updated'); }); } }
Sample Program
This component shows a count number and a button to increase it. It logs messages when the component mounts, updates, and unmounts, showing how lifecycle hooks work in the Composition API.
Vue
<template>
<div>
<p>Count: {{ count }}</p>
<button @click="increment">Increase</button>
</div>
</template>
<script setup>
import { ref, onMounted, onUnmounted, onUpdated } from 'vue';
const count = ref(0);
function increment() {
count.value++;
}
onMounted(() => {
console.log('Component mounted');
});
onUpdated(() => {
console.log('Component updated, count is', count.value);
});
onUnmounted(() => {
console.log('Component unmounted');
});
</script>OutputSuccess
Important Notes
Use onMounted to start tasks like fetching data.
Use onUnmounted to stop timers or remove event listeners to avoid memory leaks.
Hooks run only inside setup() or <script setup> in Vue 3.
Summary
Lifecycle hooks let you run code at key moments in a component's life.
Use hooks like onMounted and onUnmounted inside setup().
They help manage side effects like data fetching and cleanup.