---
title: KeepAlive Memory Management - Prevent Memory Leaks
impact: HIGH
impactDescription: Unbounded KeepAlive caching can cause severe memory issues, especially with large or numerous components
type: gotcha
tags: [vue3, keepalive, memory-leak, performance, cache, max-prop]
---
# KeepAlive Memory Management - Prevent Memory Leaks
**Impact: HIGH** - KeepAlive caches component instances in memory. Without proper limits and cleanup, this can lead to memory exhaustion, especially in applications with many routes or large component trees.
## Task Checklist
- [ ] Always use the `max` prop to limit cached instances
- [ ] Clean up resources in `onDeactivated` hook
- [ ] Monitor memory usage when using KeepAlive extensively
- [ ] Be cautious with KeepAlive on memory-heavy components
- [ ] Test on memory-constrained devices (mobile, low-spec laptops)
## The Problem: Unbounded Cache Growth
```vue
```
When users navigate through many different components, each instance stays in memory:
- Chrome memory grows continuously
- VueComponent count keeps increasing
- App becomes sluggish or crashes
## Solution: Set Cache Limits
```vue
```
**How `max` works:**
- KeepAlive uses an LRU (Least Recently Used) cache algorithm
- When cache exceeds `max`, the oldest unused component is destroyed
- This caps memory usage to a predictable maximum
### Choose `max` Based on Your Use Case
```vue
```
## Clean Up Resources in Deactivated Hook
Even with `max`, cached components hold resources. Clean up when deactivated:
```vue
```
## Third-Party Library Cleanup
Libraries that manipulate the DOM outside Vue need explicit cleanup:
```vue
```
## Avoid KeepAlive for Memory-Heavy Components
Some components should NOT be cached:
```vue
```
## Monitor Memory in Development
```vue
```
## Key Points
1. **Always set `max`** - Never use KeepAlive without a reasonable limit
2. **Clean up in `onDeactivated`** - Don't wait for unmount to release resources
3. **Exclude heavy components** - Large data grids, media players, maps
4. **Test on target devices** - Mobile users have less memory
5. **Monitor in development** - Watch for growing memory usage
## Reference
- [Vue.js KeepAlive - Max Cached Instances](https://vuejs.org/guide/built-ins/keep-alive.html#max-cached-instances)
- [Vue.js Avoiding Memory Leaks](https://v2.vuejs.org/v2/cookbook/avoiding-memory-leaks.html)
- [GitHub Issue: Memory leak with keep-alive](https://github.com/vuejs/vue/issues/6759)