By Rahul — Google Frontend Engineer
The Problem
When you switch between Vue components (tabs, routes), the component is destroyed and recreated. All state is lost — form inputs reset, scroll position gone, API data re-fetched. <keep-alive> caches the component instance instead of destroying it.
Basic Usage
<!-- Without keep-alive: component destroyed on switch -->
<component :is="currentTab" />
<!-- With keep-alive: component cached -->
<keep-alive>
<component :is="currentTab" />
</keep-alive>With Vue Router
<!-- Vue 3 -->
<router-view v-slot="{ Component }">
<keep-alive>
<component :is="Component" />
</keep-alive>
</router-view>Controlling What Gets Cached
<!-- Only cache specific components -->
<keep-alive include="SearchPage,ProductList">
<component :is="currentView" />
</keep-alive>
<!-- Exclude components from cache -->
<keep-alive exclude="CheckoutForm">
<component :is="currentView" />
</keep-alive>
<!-- Limit cache size (LRU eviction) -->
<keep-alive :max="10">
<component :is="currentView" />
</keep-alive>Lifecycle Hooks
// When component is activated (switched to)
activated() {
// Refresh data if stale
if (Date.now() - this.lastFetched > 60000) {
this.fetchData();
}
}
// When component is deactivated (switched away)
deactivated() {
// Pause expensive operations
clearInterval(this.pollingInterval);
}Production Issues
- Memory leaks: Caching too many components eats memory. Always set
:max - Stale data: Cached components show old data. Use
activatedhook to refresh - Event listeners: Listeners set in mounted() are not cleaned up on deactivate. Clean up in deactivated(), set up in activated()
Summary
keep-alive caches component instances to preserve state between switches. Use include/exclude to control caching, set :max to limit memory, and use activated/deactivated hooks to manage data freshness.