Under The Hood
frontend vue Vue 3.x

<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

react equivalent
Offscreen / Activity component (React 19 experimental `<Activity mode="hidden">`).

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.

before → after
Uncached Dynamic Component
<component :is="currentTab" /> // ❌ Destroys state and DOM on every tab switch
KeepAlive Cached Component
<KeepAlive :max="5"><component :is="currentTab" /></KeepAlive> // ✅ NEW: Preserves state in memory

Interview 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()`.

Under The Hood — a multi-depth technical interview hub.

Third-party licenses Press ⌘ K to search.