<KeepAlive>: Component Instance Caching, LRU Eviction, and onActivated Hooks
- Last updated
- Prerequisites:
- Vue dynamic components `<component :is>`
- Component lifecycle
- vue
- keep-alive
- caching
- lru
- onActivated
- onDeactivated
Read at your depth
The practical view
`<KeepAlive>` is a built-in component that caches inactive component instances instead of destroying them. When switching dynamic components (`<component :is="view">`), wrapped components stay in memory. Instead of `onMounted`/`onUnmounted`, cached components trigger `onActivated()` when shown and `onDeactivated()` when hidden. Use `include`, `exclude`, and `:max="10"` to control caching limits.
The same idea in other frameworks
Offscreen / Activity component (React 19 experimental `<Activity mode="hidden">`).Angular `RouteReuseStrategy` caching detached `RouteRef` trees.`<KeepAlive :max="10"><component :is="activeTab" /></KeepAlive>`.SvelteKit shallow routing / snapshot state restoration.Legacy vs modern
Destroyed Component State vs Cached KeepAlive Instance
Switching tabs without `<KeepAlive>` resets state and re-fetches; `<KeepAlive>` preserves form input and component state.
<component :is="currentTab" /> // ❌ Destroys state and DOM on every tab switch<KeepAlive :max="5"><component :is="currentTab" /></KeepAlive> // ✅ NEW: Preserves state in memoryInterview gotchas
Context
Interviewers test your knowledge of KeepAlive-specific lifecycle hooks.
The mechanical answer
No. `onMounted` only runs *once* when the component is initially created. When switching away, `onUnmounted` is bypassed and **`onDeactivated`** runs. When returning to the cached component, `onMounted` does *not* run again; instead, **`onActivated`** executes.
Trap
If you fetch fresh data inside `onMounted()`, a cached KeepAlive component will never re-fetch data on revisit. Move re-validation logic to `onActivated()`.
Context
Checks understanding of the internal cache eviction algorithm.
The mechanical answer
`<KeepAlive>` implements a **Least Recently Used (LRU)** eviction policy. When the cache size exceeds `:max`, the component instance that has been inactive for the longest time is evicted from the cache map and permanently unmounted (running its `onUnmounted` hook).
Trap
Setting `:max` too high can cause excessive memory consumption on mobile devices as dozens of full DOM subtrees remain pinned in RAM.