JAVASCRIPT

Optimize Vue 3 Re-renders with `v-memo` Directive

Boost Vue 3 application performance by using the `v-memo` directive to prevent unnecessary re-renders of static or memoized template parts, improving efficiency.

<template>
  <div>
    <p>Count: {{ count }}</p>
    <button @click="count++">Increment Count</button>

    <!-- This list item will only re-render if 'item.id' or 'item.value' changes -->
    <!-- The first v-for item demonstrates v-memo in a list context -->
    <div v-for="item in items" :key="item.id">
      <div v-memo="[item.id, item.value]">
        <p>ID: {{ item.id }}</p>
        <p>Value: {{ item.value }}</p>
        <p>Count (from parent, will NOT update if memoized): {{ count }}</p>
      </div>
    </div>

    <hr>

    <!-- This block will only re-render if 'someCondition' changes -->
    <div v-memo="[someCondition]">
      <h3>Memoized Block</h3>
      <p>This content is only updated when 'someCondition' changes.</p>
      <p>Current Count (from parent, will NOT update if memoized): {{ count }}</p>
    </div>

    <button @click="someCondition = !someCondition">Toggle Condition ({{ someCondition }})</button>
  </div>
</template>

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

const count = ref(0);
const someCondition = ref(false);

const items = reactive([
  { id: 1, value: 'Item A' },
  { id: 2, value: 'Item B' }
]);

// To demonstrate v-memo update, uncomment this after some interactions
// setTimeout(() => {
//   items[0].value = 'Updated Item A';
// }, 5000);

</script>
How it works: The `v-memo` directive in Vue 3 is a performance optimization tool that allows you to memoize a template subtree. If all the values in the `v-memo` dependency array remain the same between re-renders, Vue will skip updating that part of the DOM entirely. This is particularly useful for static content within frequently re-rendering components, or in `v-for` loops where only specific item properties should trigger an update, significantly reducing rendering overhead.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs