0
0
Vueframework~8 mins

Lifecycle hooks in Composition API in Vue - Performance & Optimization

Choose your learning style9 modes available
Performance: Lifecycle hooks in Composition API
MEDIUM IMPACT
This affects the timing of code execution during component rendering and updates, impacting interaction responsiveness and rendering smoothness.
Running heavy synchronous code inside lifecycle hooks
Vue
import { onMounted } from 'vue';
onMounted(() => {
  setTimeout(() => {
    // heavy task deferred
    for (let i = 0; i < 1_000_000_000; i++) {}
  }, 0);
});
Deferring heavy tasks lets the browser render first and respond to user input faster.
📈 Performance GainNon-blocking mount, improves INP by 80-90%.
Running heavy synchronous code inside lifecycle hooks
Vue
import { onMounted } from 'vue';
onMounted(() => {
  // heavy synchronous task
  for (let i = 0; i < 1_000_000_000; i++) {}
});
Heavy synchronous code blocks the main thread during component mount, delaying rendering and user interaction.
📉 Performance CostBlocks rendering for 100+ ms, causing poor INP and delayed LCP.
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Heavy synchronous code in onMountedMinimalBlocks rendering causing multiple reflowsHigh due to delayed paint[X] Bad
Deferred heavy code with setTimeoutMinimalSingle reflow after renderLow paint cost[OK] Good
Direct DOM style changes in multiple hooksMultiple style changes2+ reflows per updateHigh paint cost causing jank[X] Bad
Reactive state with watchEffect for DOM updatesSingle batched DOM updateSingle reflowLow paint cost[OK] Good
Rendering Pipeline
Lifecycle hooks run JavaScript code at specific component phases, affecting style calculation, layout, and paint depending on DOM changes triggered.
JavaScript Execution
Style Calculation
Layout
Paint
⚠️ BottleneckJavaScript Execution blocking Style Calculation and Layout
Core Web Vital Affected
INP
This affects the timing of code execution during component rendering and updates, impacting interaction responsiveness and rendering smoothness.
Optimization Tips
1Avoid heavy synchronous code inside lifecycle hooks to prevent blocking rendering.
2Defer expensive tasks using timers or async methods to improve input responsiveness.
3Use reactive state and watchers to batch DOM updates and minimize reflows.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main performance risk of running heavy synchronous code inside onMounted?
AIt increases bundle size significantly.
BIt blocks rendering and delays user interaction.
CIt causes layout shifts after paint.
DIt reduces network request speed.
DevTools: Performance
How to check: Record a performance profile during component mount and update; look for long tasks and scripting blocking time.
What to look for: Look for long scripting tasks during lifecycle hooks and multiple reflows or layout thrashing in the flame chart.