0
0
Vueframework~8 mins

Keep-alive for caching components in Vue - Performance & Optimization

Choose your learning style9 modes available
Performance: Keep-alive for caching components
MEDIUM IMPACT
This affects page interaction speed by caching component state and reducing re-renders during navigation.
Caching Vue components to improve navigation speed
Vue
<template>
  <keep-alive>
    <component :is="currentView" />
  </keep-alive>
</template>

<script setup>
import { ref } from 'vue'
const currentView = ref('HomeView')
</script>
Components are cached in memory, preserving state and avoiding re-renders on navigation.
📈 Performance GainReduces re-renders and layout recalculations, improving interaction responsiveness (INP).
Caching Vue components to improve navigation speed
Vue
<template>
  <component :is="currentView" />
</template>

<script setup>
import { ref } from 'vue'
const currentView = ref('HomeView')
</script>
Components are destroyed and recreated on each navigation, causing full re-renders and state loss.
📉 Performance CostTriggers full re-render and layout recalculation on every component switch, increasing INP.
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Without keep-aliveDestroys and recreates DOM nodes on each switchTriggers 1 reflow per component switchHigh paint cost due to full redraw[X] Bad
With keep-aliveReuses cached DOM nodes, no destructionNo reflow on cached component switchLow paint cost, only compositing[OK] Good
Rendering Pipeline
Keep-alive caches component instances in memory, so switching views reuses existing DOM nodes without full re-layout or paint.
Layout
Paint
Composite
⚠️ BottleneckLayout and Paint stages due to component destruction and recreation
Core Web Vital Affected
INP
This affects page interaction speed by caching component state and reducing re-renders during navigation.
Optimization Tips
1Use keep-alive to cache components and preserve their state during navigation.
2Caching reduces layout recalculations and paint, improving interaction speed (INP).
3Avoid unnecessary component destruction to prevent costly reflows and repaints.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main performance benefit of using keep-alive in Vue?
AIt reduces JavaScript bundle size
BIt caches components to avoid re-rendering and preserve state
CIt improves SEO by pre-rendering components
DIt lazy loads components on demand
DevTools: Performance
How to check: Record a session while switching components with and without keep-alive. Look for layout and paint events.
What to look for: Reduced layout and paint times when using keep-alive indicate better performance.