Performance: Composable with lifecycle hooks
This affects how efficiently Vue components manage side effects and resource cleanup during rendering and interaction.
import { onMounted, onUnmounted } from 'vue'; export function useTimer() { let intervalId = null; onMounted(() => { intervalId = setInterval(() => { console.log('tick'); }, 1000); }); onUnmounted(() => { clearInterval(intervalId); }); }
import { onMounted, onUnmounted } from 'vue'; export function useTimer() { let intervalId = null; onMounted(() => { intervalId = setInterval(() => { console.log('tick'); }, 1000); }); // Missing cleanup on unmount }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Composable without cleanup | Minimal | 0 | Low but ongoing CPU usage | [X] Bad |
| Composable with proper lifecycle cleanup | Minimal | 0 | Low and stops when unused | [OK] Good |
onMounted lifecycle hook inside a Vue 3 composable?onMounted are named exports, so use curly braces in import.onMounted is a function that takes a callback, so call it with a function argument.import { ref, onMounted } from 'vue';
export function useLogger() {
const message = ref('Hello');
onMounted(() => {
console.log(message.value);
});
return { message };
}message ref is initialized with the string 'Hello'.message.value, which is 'Hello'.import { onMounted, onUnmounted } from 'vue';
export function useTimer() {
let timer = null;
onMounted(() => {
timer = setInterval(() => console.log('tick'), 1000);
});
onUnmounted(() => {
clearInterval(timer);
});
return {};
}timer is declared in composable scope and updated in onMounted, accessible in onUnmounted.onMounted sets interval, onUnmounted clears it correctly to avoid memory leaks.onMounted.onUnmounted to abort the fetch using an AbortController.onMounted to start fetch and onUnmounted to abort fetch with an AbortController -> Option BPass the test and this pattern moves unknown