What is <keep-alive>?
<keep-alive> is a special built-in Vue component that lets you cache component state and DOM so that on re-display they are not recreated, but restored from memory.
Put simply:
<keep-alive>keeps a component "alive" even when it is temporarily removed from the screen. It is not destroyed, only hidden.
This is one of the most important optimization tools.
Why is <keep-alive> needed?
Normally, when a component is hidden via v-if:
- it is removed from the DOM,
unmountedis called,- data and state are lost.
For example, switching tabs:
Tab A -> Tab B -> Tab A
If the component is not cached, it is created from scratch every time. This is bad if it contains:
- heavy computations
- forms with filled-in data
- third-party plugins
- state that needs to be preserved
<keep-alive> solves this.
Usage example
<keep-alive>
<ComponentA v-if="showA" />
</keep-alive>Now:
- the component is created once
- when hidden it is not destroyed, but "put to sleep"
- when shown again it is restored instantly
Lifecycle with keep-alive
The component gets two special hooks:
activated()
The component is active again (shown).
deactivated()
The component is hidden, but not destroyed.
Example:
export default {
activated() {
console.log("Component activated");
},
deactivated() {
console.log("Component hidden");
}
}Filtering components (include / exclude)
You can specify which components to cache:
<keep-alive include="UserPage,ProfilePage">
<component :is="currentPage" />
</keep-alive>include / exclude accept:
- a string:
"CompA,CompB" - an array:
['CompA', 'CompB'] - a RegExp:
/^Admin/
Limiting cache size - max
<keep-alive :max="5">
<component :is="currentPage" />
</keep-alive>Vue keeps only the last 5 components; the rest are removed.
When should you not use <keep-alive>?
- when the component depends on the URL (for example, router pages)
- when you need to run code on every entry into the component (for example, refreshing data)
- when the component is too heavy and caching it would use too much memory
Usage with Vue Router
The classic case, caching pages:
<keep-alive>
<router-view />
</keep-alive>This significantly speeds up transitions between routes.
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.