KeepAlive and cached components
Why switching dynamic components throws away their state, how <KeepAlive> caches instances instead, and include, exclude, max, onActivated and onDeactivated.
KeepAlive and cached components
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- By default, switching a dynamic `<component :is>` away from a component unmounts it, so any state it held — form input, scroll position, a fetched list — is gone when you switch back.
- Wrapping the dynamic component in `<KeepAlive>` moves the inactive instance into a cache instead of destroying it, so switching back reuses the same instance with its state intact.
- `include` and `exclude` take a comma-separated string, a RegExp or an array, matched against the component's `name`; a `<script setup>` component gets its name from its filename since Vue 3.2.34.
- `max` turns the cache into an LRU cache: once the limit is reached, the least recently used instance is destroyed to make room, which keeps memory bounded.
- A cached component gets `onActivated` when it is inserted (including the first mount) and `onDeactivated` when it is moved into the cache (and on final unmount), so timers, polling and subscriptions belong there rather than only in `onMounted`/`onUnmounted`.
Switching components throws state away
Vue’s dynamic component element swaps which component renders based on a value:
<script setup>
import { ref, shallowRef } from 'vue'
import ProfileTab from './ProfileTab.vue'
import BillingTab from './BillingTab.vue'
const tabs = { Profile: ProfileTab, Billing: BillingTab }
const current = shallowRef(ProfileTab)
</script>
<template>
<button v-for="(comp, label) in tabs" :key="label" @click="current = comp">
{{ label }}
</button>
<component :is="current" />
</template>
(shallowRef is used because a component definition doesn’t need deep reactivity — see shallow reactivity.)
Every time current changes, Vue unmounts the old component and mounts a fresh instance of the new one. That’s the right default most of the time: an unmounted component frees its memory, its watchers stop, and the next mount starts clean. It also means everything the old instance held is gone — typed-in form fields, a scroll position, an expanded accordion, data fetched in onMounted. Switch back and you start over, possibly with another network request.
For tabs, wizard steps and list/detail views, that’s a bug the user notices.
Keep the instance, don’t rebuild it
<KeepAlive> wraps the dynamic component and changes what “switching away” means:
<template>
<KeepAlive>
<component :is="current" />
</KeepAlive>
</template>
Now when current changes, the outgoing instance is detached from the DOM and stored in a cache instead of being unmounted. Its reactive state, its child components and its DOM nodes all survive. Switching back re-inserts that same instance.
A useful picture is a coat check. Without <KeepAlive>, leaving the room means throwing your coat away and buying a new one when you come back. With it, you hand the coat over, get a ticket, and pick up the same coat — pockets and all.
Like <Transition>, <KeepAlive> wraps a single direct child, and it works through its default slot, which is why slots are a prerequisite. The child is usually a <component :is>, but a v-if/v-else pair of components works too.
Choosing what to cache: include, exclude, max
Caching everything isn’t always wise. A component that shows live data may be better off remounting so it starts fresh. include and exclude control which components are kept:
<!-- comma-separated string -->
<KeepAlive include="ProfileTab,BillingTab">
<component :is="current" />
</KeepAlive>
<!-- RegExp or array need v-bind -->
<KeepAlive :exclude="/Live/">
<component :is="current" />
</KeepAlive>
<KeepAlive :include="['ProfileTab', 'BillingTab']">
<component :is="current" />
</KeepAlive>
The match is against the component’s name. Since Vue 3.2.34, a <script setup> single-file component infers its name from its filename, so ProfileTab.vue is named ProfileTab without you declaring anything. If you need a different name, Vue 3.3 added the defineOptions({ name: '...' }) macro covered in script setup and compiler macros.
max bounds the cache:
<KeepAlive :max="10">
<component :is="current" />
</KeepAlive>
With a max, <KeepAlive> acts as an LRU (least recently used) cache. When adding an instance would exceed the limit, the instance that was accessed longest ago is destroyed — properly unmounted — to make room. This matters when the dynamic component is something like a per-record detail view: without a cap, every record the user ever opened stays in memory.
Lifecycle of a cached instance
Caching adds two states to the lifecycle. A cached component is deactivated when it’s moved into the cache and activated when it’s put back. Two hooks match:
<script setup>
import { ref, onActivated, onDeactivated } from 'vue'
const rates = ref([])
let timer
async function refresh() {
rates.value = await (await fetch('/api/rates')).json()
}
onActivated(() => {
// runs on the first mount AND every time it comes back from the cache
refresh()
timer = setInterval(refresh, 10_000)
})
onDeactivated(() => {
// runs when it goes into the cache AND on final unmount
clearInterval(timer)
})
</script>
The key detail: onUnmounted does not run when a kept-alive component is switched away, because it isn’t unmounted. If you start a timer in onMounted and stop it in onUnmounted, the timer keeps running while the component sits invisible in the cache. Moving that pair into onActivated/onDeactivated fixes it, and because onActivated also fires on initial mount and onDeactivated on final unmount, you don’t need both pairs.
These hooks fire for every component in the cached subtree, not only the root, so a deeply nested chart inside a cached tab can pause itself too.
KeepAlive with routes
The most common real-world use is caching routed pages, such as keeping a search results list intact when the user opens an item and presses Back. Vue Router exposes the matched component through a slot so you can wrap it:
<RouterView v-slot="{ Component }">
<KeepAlive :include="['SearchResults']">
<component :is="Component" />
</KeepAlive>
</RouterView>
The router side of this is covered in nested routes and named views. When combined with <Transition> and <Suspense>, the nesting order matters: <Transition> outside, then <KeepAlive>, then <Suspense>, then the component.
What the video covers
LearnVue starts from the problem — a dynamic component that loses its state when you switch away — and shows keep-alive caching it, framing it as both a UX and a performance choice. It dates from 2021 and may show the kebab-case <keep-alive> spelling, which still works (and is required in in-DOM templates); the docs use PascalCase <KeepAlive> in single-file components. The max LRU behavior and the Composition API onActivated/onDeactivated hooks above fill in what the video leaves light. Codevolution’s three-minute clip below is a quick Vue 3 demo of the same state-loss problem.
Where this fits
Caching keeps instances alive. The next built-in, Teleport, keeps an instance in place logically but renders its DOM somewhere else. The idea of caching comes back in performance optimization, where <KeepAlive> is one tool for avoiding repeated expensive mounts.
Check yourself
A tabbed settings page uses `<component :is="currentTab" />`. A user half-fills a form in one tab, switches tabs, and comes back to an empty form. Why, and what is the one-line fix?
Switching the `:is` value unmounts the old component instance, which destroys its reactive state, and coming back creates a fresh instance with initial state. Wrapping it as `<KeepAlive><component :is="currentTab" /></KeepAlive>` makes Vue deactivate and cache the instance instead of unmounting it, so the half-filled form survives.
You add `<KeepAlive include="UserList">` but `UserList.vue` is still not being cached. What should you check?
`include` matches the component's `name` option. With `<script setup>` on Vue 3.2.34 or later, the name is inferred from the filename, so `UserList.vue` should match; if the file is named differently, or the component is defined in a way that has no inferred name, it won't. Also check the string is exactly the name with no stray spaces in the comma-separated list, or use an array or RegExp.
A dashboard widget starts a `setInterval` poll in `onMounted` and clears it in `onUnmounted`. Inside `<KeepAlive>`, what goes wrong, and how do you fix it?
When the widget is switched away it is deactivated, not unmounted, so `onUnmounted` never runs and the interval keeps polling in the background while the widget is hidden. Starting the poll in `onActivated` and clearing it in `onDeactivated` fixes it, since `onActivated` also fires on the first mount and `onDeactivated` also fires on the final unmount.
What does `:max="5"` do, and why would you set it?
It caps the cache at five component instances and makes it behave like an LRU cache: when a sixth would be added, the least recently accessed cached instance is destroyed. Without it, every distinct component ever shown stays in memory, which can grow without bound in an app with many views or per-record components.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.