Tutorials Logic, IN info@tutorialslogic.com
Navigation
Home About Us Contact Us Blogs FAQs
Tutorials
All Tutorials
Services
Academic Projects Resume Writing Website Development
Practice
Quiz Challenge Interview Questions Certification Practice
Tools
Online Compiler JSON Formatter Regex Tester CSS Unit Converter Color Picker
Compiler Tools

Vue Performance v memo, KeepAlive, shallowRef: Tutorial, Examples, FAQs & Interview Tips

Performance Techniques Overview

TechniqueWhat it doesWhen to use
v-memoSkip re-rendering subtree if deps unchangedLarge lists with complex items
KeepAliveCache inactive componentsTab switching, route caching
shallowRefOnly track top-level reactivityLarge objects where deep tracking is wasteful
markRawExclude object from reactivityThird-party instances, large static data
Lazy loadingLoad components on demandLarge components, routes
Virtual scrollingRender only visible itemsLists with 1000+ items
v-memo, KeepAlive, shallowRef, markRaw
<template>
  <div>
    <!-- v-memo - skip re-render if deps unchanged -->
    <!-- Only re-renders when item.id or selected changes -->
    <div
      v-for="item in list"
      :key="item.id"
      v-memo="[item.id, item.selected]"
    >
      <p>{{ item.name }}</p>
      <span v-if="item.selected">x Selected</span>
    </div>

    <!-- KeepAlive - cache inactive components -->
    <div class="tabs">
      <button v-for="tab in tabs" :key="tab" @click="currentTab = tab">{{ tab }}</button>
    </div>
    <KeepAlive
      :include="['HomeTab', 'ProfileTab']"
      :exclude="['SettingsTab']"
      :max="5"
    >
      <component :is="currentTabComponent" />
    </KeepAlive>
  </div>
</template>

<script setup>
import { ref, shallowRef, markRaw, reactive } from 'vue'
import HomeTab     from './HomeTab.vue'
import ProfileTab  from './ProfileTab.vue'
import SettingsTab from './SettingsTab.vue'

// shallowRef - only top-level reactivity (no deep tracking)
// Good for large objects where you replace the whole value
const bigData = shallowRef({ items: new Array(10000).fill(0) })

function updateData() {
  // Must replace the whole object to trigger reactivity
  bigData.value = { items: new Array(10000).fill(1) }
  // bigData.value.items[0] = 1  // WON'T trigger update
}

// markRaw - exclude from reactivity system entirely
// Good for: third-party class instances, large static data, Map/Set
import { Chart } from 'chart.js'
const chartInstance = markRaw(new Chart(/* ... */))
// chartInstance won't be made reactive - saves memory

// Also useful for component references in reactive objects
const state = reactive({
  // Without markRaw, Vue would try to make HomeTab reactive (wasteful)
  currentComponent: markRaw(HomeTab),
})

const list = ref(Array.from({ length: 1000 }, (_, i) => ({
  id: i, name: `Item ${i}`, selected: false
})))

const tabs = ['Home', 'Profile', 'Settings']
const currentTab = ref('Home')
const tabMap = { Home: HomeTab, Profile: ProfileTab, Settings: SettingsTab }
const currentTabComponent = computed(() => tabMap[currentTab.value])
</script>
<template>
  <div>
    <!-- Use v-show for frequent toggles -->
    <div v-show="isVisible">Frequently toggled</div>

    <!-- Use v-if for rare conditions -->
    <HeavyComponent v-if="showHeavy" />

    <!-- Lazy load heavy components -->
    <Suspense>
      <template #default><LazyChart /></template>
      <template #fallback><div>Loading chart...</div></template>
    </Suspense>

    <!-- v-once - render once, never update -->
    <footer v-once>
      <p>© {{ year }} My App. All rights reserved.</p>
    </footer>
  </div>
</template>

<script setup>
import { ref, defineAsyncComponent } from 'vue'

// Lazy load heavy component
const LazyChart = defineAsyncComponent(() => import('./HeavyChart.vue'))

const isVisible = ref(true)
const showHeavy = ref(false)
const year = new Date().getFullYear()

// Performance best practices:
// 1. Use computed for derived data (cached)
// 2. Use v-memo for expensive list items
// 3. Use KeepAlive for tab/route caching
// 4. Use shallowRef for large objects you replace wholesale
// 5. Use markRaw for non-reactive third-party instances
// 6. Lazy load routes and heavy components
// 7. Use virtual scrolling for 1000+ item lists (vue-virtual-scroller)
// 8. Avoid large reactive objects - use shallowReactive for flat data
// 9. Use v-once for truly static content
// 10. Profile with Vue DevTools before optimizing
</script>

Deep Dive: Performance in Real Projects

Understanding Performance is not just about syntax. In production applications, this topic directly affects maintainability, debugging speed, and team collaboration. Focus on readability, small reusable patterns, and predictable state flow when implementing Performance.

A practical approach is to first implement the simplest working version, then refactor into reusable pieces (components/composables/stores) only when duplication appears. This helps keep your Vue codebase clean while avoiding over-engineering.

Common Mistakes to Avoid

  • Mixing too many responsibilities in one component instead of separating logic by concern.
  • Skipping meaningful naming for variables, emits, and component props.
  • Ignoring edge cases like empty data, loading states, and error handling.
  • Optimizing too early before measuring real bottlenecks in browser devtools.
  • Not creating small test scenarios to validate behavior after each change.

Mini Practice Checklist

  1. Build a small demo focused only on Performance.
  2. Add one edge case (empty/loading/error) and handle it cleanly.
  3. Refactor repeated logic into a reusable function/composable.
  4. Add clear comments only where logic is non-obvious.
  5. Verify behavior with manual testing and Vue Devtools.
Key Takeaways
  • This chapter on Performance focuses on practical Vue 3 patterns used in real projects.
  • Prefer the Composition API with script setup for cleaner and more scalable component logic.
  • Keep components focused and move reusable logic into composables when complexity grows.
  • Use Vue Devtools to inspect component state, props, emits, and performance during development.
  • Write small experiments for each concept before applying it in production code.
  • After finishing this chapter, continue to the next related topic in the Vue roadmap.

Ready to Level Up Your Skills?

Explore 500+ free tutorials across 20+ languages and frameworks.