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
With Vue Router
Controlling What Gets Cached
Lifecycle Hooks
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.