0
0
Vueframework~5 mins

v-memo for conditional memoization in Vue

Choose your learning style9 modes available
Introduction

v-memo helps Vue remember parts of your template so it doesn't redo work when it doesn't need to. This makes your app faster by skipping repeated work.

When you have a big list and only some items change, so you want to skip re-rendering unchanged items.
When you want to avoid expensive calculations or DOM updates unless certain data changes.
When you want to improve performance in a component that updates often but only parts of it depend on some data.
When you want to control exactly when Vue should update a part of your template based on specific conditions.
Syntax
Vue
<template>
  <div v-memo="[condition1, condition2]">
    <!-- content that updates only if conditions change -->
  </div>
</template>

The v-memo directive takes an array of values to watch.

Vue skips re-rendering the element if these values do not change.

Examples
This paragraph only updates when count changes.
Vue
<template>
  <p v-memo="[count]">Count is {{ count }}</p>
</template>
Each list item only re-renders if its item.value changes.
Vue
<template>
  <ul>
    <li v-for="item in items" :key="item.id" v-memo="[item.value]">
      {{ item.value }}
    </li>
  </ul>
</template>
This block updates only if user.name or user.age changes.
Vue
<template>
  <div v-memo="[user.name, user.age]">
    <p>Name: {{ user.name }}</p>
    <p>Age: {{ user.age }}</p>
  </div>
</template>
Sample Program

Here, the paragraph showing count uses v-memo with [count]. It only re-renders when count changes. The name paragraph updates normally.

Clicking 'Increment Count' updates the count and re-renders the count paragraph only. Clicking 'Change Name' updates the name but does not re-render the count paragraph.

Vue
<template>
  <div>
    <button @click="incrementCount">Increment Count</button>
    <button @click="changeName">Change Name</button>

    <p v-memo="[count]">Count: {{ count }}</p>
    <p>Name: {{ name }}</p>
  </div>
</template>

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

const count = ref(0)
const name = ref('Alice')

function incrementCount() {
  count.value++
}

function changeName() {
  name.value = name.value === 'Alice' ? 'Bob' : 'Alice'
}
</script>
OutputSuccess
Important Notes

Time complexity: Using v-memo reduces unnecessary re-renders, improving performance especially in large or complex templates.

Space complexity: Minimal extra memory is used to track the memoized values.

A common mistake is not including all relevant reactive values in the v-memo array, causing stale or incorrect UI.

Use v-memo when you want fine control over updates. For simple cases, Vue's normal reactivity is enough.

Summary

v-memo helps Vue skip re-rendering parts of the template when certain values don't change.

It takes an array of values to watch and only updates if these change.

This improves performance by avoiding unnecessary work.