--- title: KeepAlive Component Best Practices impact: HIGH impactDescription: KeepAlive caches component instances; misuse causes stale data, memory growth, or unexpected lifecycle behavior type: best-practice tags: [vue3, keepalive, cache, performance, router, dynamic-components] --- # KeepAlive Component Best Practices **Impact: HIGH** - `` caches component instances instead of destroying them. Use it to preserve state across switches, but manage cache size and freshness explicitly to avoid memory growth or stale UI. ## Task List - Use KeepAlive only where state preservation improves UX - Set a reasonable `max` to cap cache size - Declare component names for include/exclude matching - Use `onActivated`/`onDeactivated` for cache-aware logic - Decide how and when cached views refresh their data - Avoid caching memory-heavy or security-sensitive views ## When to Use KeepAlive Use KeepAlive when switching between views where state should persist (tabs, multi-step forms, dashboards). Avoid it when each visit should start fresh. **BAD:** ```vue ``` **GOOD:** ```vue ``` ## When NOT to Use KeepAlive - Search or filter pages where users expect fresh results - Memory-heavy components (maps, large tables, media players) - Sensitive flows where data must be cleared on exit - Components with heavy background activity you cannot pause ## Limit and Control the Cache Always cap cache size with `max` and restrict caching to specific components when possible. ```vue ``` ## Ensure Component Names Match include/exclude `include` and `exclude` match the component `name` option. Explicitly set names for reliable caching. ```vue ``` ```vue ``` ## Cache Invalidation Strategies Vue 3 has no direct API to remove a specific cached instance. Use keys or dynamic include/exclude to force refreshes. ```vue ``` ## Lifecycle Hooks for Cached Components Cached components are not destroyed on switch. Use activation hooks for refresh and cleanup. ```vue ``` ## Router Caching and Freshness Decide whether navigation should show cached state or a fresh view. A common pattern is to key by route when params change. ```vue ``` If you want cache reuse but fresh data, refresh in `onActivated` and compare query/params before fetching.