Composable functions help you reuse code in Vue components. Lifecycle hooks inside composables let you run code at key moments like when a component starts or stops.
0
0
Composable with lifecycle hooks in Vue
Introduction
You want to share logic like fetching data or timers between components.
You need to run setup or cleanup code when a component mounts or unmounts.
You want to keep your component code clean by moving side effects to composables.
You want to react to component lifecycle events inside reusable functions.
Syntax
Vue
import { onMounted, onUnmounted } from 'vue'; export function useExample() { onMounted(() => { // code to run when component mounts }); onUnmounted(() => { // code to run when component unmounts }); return { // reactive data or methods }; }
Use onMounted to run code after the component appears on screen.
Use onUnmounted to clean up when the component is removed.
Examples
This composable logs a message when the component mounts.
Vue
import { onMounted } from 'vue'; export function useLogger() { onMounted(() => { console.log('Component is ready'); }); }
This composable counts seconds while the component is visible and stops when it unmounts.
Vue
import { onMounted, onUnmounted, ref } from 'vue'; export function useTimer() { const seconds = ref(0); let intervalId; onMounted(() => { intervalId = setInterval(() => { seconds.value++; }, 1000); }); onUnmounted(() => { clearInterval(intervalId); }); return { seconds }; }
Sample Program
This Vue component uses a composable useTimer that starts counting seconds when the component mounts and stops when it unmounts. The seconds count updates every second and shows on screen.
Vue
<template>
<div>
<p>Seconds passed: {{ seconds }}</p>
</div>
</template>
<script setup>
import { ref, onMounted, onUnmounted } from 'vue';
function useTimer() {
const seconds = ref(0);
let intervalId;
onMounted(() => {
intervalId = setInterval(() => {
seconds.value++;
}, 1000);
});
onUnmounted(() => {
clearInterval(intervalId);
});
return { seconds };
}
const { seconds } = useTimer();
</script>OutputSuccess
Important Notes
Always clear timers or subscriptions in onUnmounted to avoid memory leaks.
Composable lifecycle hooks run in the component that calls them.
Summary
Composable functions let you reuse logic across components.
Use lifecycle hooks inside composables to run code at component start and cleanup.
This keeps your components clean and your code organized.