--- title: Use KeepAlive to Preserve Dynamic Component State impact: MEDIUM impactDescription: Dynamic component switching destroys and recreates components, losing all internal state unless wrapped in KeepAlive type: best-practice tags: [vue3, dynamic-components, keepalive, component-is, state-preservation, performance] --- # Use KeepAlive to Preserve Dynamic Component State **Impact: MEDIUM** - When switching between components using ``, Vue destroys the old component and creates a new one. All internal state (form inputs, scroll position, fetched data) is lost. Wrapping dynamic components in `` caches them and preserves their state. ## Task Checklist - [ ] Wrap `` with `` when state preservation is needed - [ ] Use `include` and `exclude` to control which components are cached - [ ] Use `max` to limit cache size and prevent memory issues - [ ] Implement `onActivated`/`onDeactivated` hooks for cache-aware logic - [ ] Consider NOT using KeepAlive when fresh state is desired ## The Problem: State Loss ```vue ``` If TabA has a form with user input, switching to TabB and back resets all input. ## Solution: KeepAlive ```vue ``` Now TabA's state persists even when TabB is displayed. ## Controlling What Gets Cached ### Include/Exclude by Name Only cache specific components: ```vue ``` **Important:** Components must have a `name` option to be matched: ```vue ``` Or in Vue 3.3+ with ` ``` ### Limit Cache Size Prevent memory issues with many cached components: ```vue ``` When cache exceeds `max`, the least recently accessed component is destroyed. ## Lifecycle Hooks: onActivated and onDeactivated Cached components need special lifecycle hooks: ```vue ``` **Common use cases for activation hooks:** - Refresh stale data when returning to a tab - Resume/pause video or audio playback - Reconnect/disconnect WebSocket connections - Save/restore scroll position - Track analytics for tab views ## KeepAlive with Vue Router For route-based caching: ```vue ``` **With transition:** ```vue ``` ## When NOT to Use KeepAlive Don't cache when: ```vue ``` - Form should reset between visits - Data must be fresh (real-time dashboards) - Component has significant memory footprint - Security-sensitive data should be cleared ## Performance Considerations ```vue ``` ## Reference - [Vue.js KeepAlive](https://vuejs.org/guide/built-ins/keep-alive.html) - [Vue.js Dynamic Components](https://vuejs.org/guide/essentials/component-basics.html#dynamic-components)