Performance: Lifecycle hooks in Composition API
This affects the timing of code execution during component rendering and updates, impacting interaction responsiveness and rendering smoothness.
import { onMounted } from 'vue'; onMounted(() => { setTimeout(() => { // heavy task deferred for (let i = 0; i < 1_000_000_000; i++) {} }, 0); });
import { onMounted } from 'vue'; onMounted(() => { // heavy synchronous task for (let i = 0; i < 1_000_000_000; i++) {} });
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Heavy synchronous code in onMounted | Minimal | Blocks rendering causing multiple reflows | High due to delayed paint | [X] Bad |
| Deferred heavy code with setTimeout | Minimal | Single reflow after render | Low paint cost | [OK] Good |
| Direct DOM style changes in multiple hooks | Multiple style changes | 2+ reflows per update | High paint cost causing jank | [X] Bad |
| Reactive state with watchEffect for DOM updates | Single batched DOM update | Single reflow | Low paint cost | [OK] Good |
onMounted hook runs after the component is inserted into the DOM.onMounted is the correct choice.onUnmounted hook inside the setup() function?import { onUnmounted } from 'vue';onUnmounted(() => { /* cleanup */ });import { ref, onMounted } from 'vue';
export default {
setup() {
const count = ref(0);
onMounted(() => {
count.value = 5;
console.log('Mounted count:', count.value);
});
return { count };
}
}count starts at 0, then inside onMounted it is set to 5 and logged.import { onMounted } from 'vue';
export default {
setup() {
onMounted = () => {
console.log('Mounted');
};
}
}onMounted instead of calling it with a callback.onMounted(() => { ... }), not assignment.import { ref, onMounted, onUnmounted } from 'vue';
export default {
setup() {
const data = ref(null);
let timer;
onMounted(() => {
fetch('/api/data').then(res => res.json()).then(json => data.value = json);
timer = setInterval(() => console.log('tick'), 1000);
});
onUnmounted(() => {
clearInterval(timer);
});
return { data };
}
} uses onMounted to fetch data and start the timer, which is correct.import { ref, onMounted, onUnmounted } from 'vue';
export default {
setup() {
const data = ref(null);
let timer;
onMounted(() => {
fetch('/api/data').then(res => res.json()).then(json => data.value = json);
timer = setInterval(() => console.log('tick'), 1000);
});
onUnmounted(() => {
clearInterval(timer);
});
return { data };
}
} uses onUnmounted to clear the timer, preventing memory leaks.Pass the test and this pattern moves unknown