Blog>
Snippets

Optimizing Re-rendering with v-memo Directive

Use the v-memo directive to memorize the output of a rendered template chunk to avoid unnecessary re-rendering of identical DOM content.
<template>
  <div>
    <span v-memo="[complexComputedValue]">
      {{ complexComputedValue }}
    </span>
  </div>
</template>

<script>
import { computed } from 'vue';

export default {
  props: ['items'],
  setup(props) {
    // 'complexComputedValue' is a heavy-computed value that should not recompute
    // if 'items' prop doesn't change.
    const complexComputedValue = computed(() => {
      // Assume a heavy computation is done here
      return props.items.reduce((sum, item) => sum + item.value, 0);
    });

    return {
      complexComputedValue
    };
  }
};
</script>
This Vue.js component uses the v-memo directive to memoize the output of a rendered template chunk. The 'complexComputedValue' is computed once, and only re-computed when 'items' prop changes, thus avoiding the unnecessary re-rendering of the DOM that represents this computed value.