Vue 3 Performance Directives: v-memo
Vue 3 has provided us with several significant performance improvements out of the box but has also introduced some extra manual features that can help up improve our app performance.
In this article, we are going to discuss a new directive called v-memo
. This directive has been introduced in Vue 3 and to the best of my knowledge currently not available in Vue 2. The aim of this directive is to help you improve the performance of your medium / large Vue.js application and is not intended to be used in small applications.
What does v-memo do?
The v-memo directive memoizes a sub-tree of a template - meaning that it stores the result of previous renders to speed up future ones.
It accepts a dependency array and will only re-render if one of the values in the array has changed. Basically, we're saying to only update this sub-tree if one of these values changes.
Usage
<template>
<p v-memo="[msg]">{{ msg }}</p>
</template>
Going on with this logic where changes in the value of our dependencies will trigger an update, passing in an empty dependency array will function the same as using v-once where it will never re-render.
<template>
<p v-once>{{ msg }}</p>
<p v-memo="[]">{{ msg }}</p>
</template>
Let’s see how we can use it in a basic example
<script setup>
import { ref } from 'vue'
const subscribers = ref(4000)
const views = ref(10000)
const likes = ref(3000)
</script>
<template>
<div>
<div v-memo="[subscribers]">
<p>Subscribers: {{ subscribers }}</p>
<p>Views: {{ views }}</p>
<p>Likes: {{ likes }}</p>
</div>
<button @click="subscribers++">Subscribers++</button>
<button @click="views++">Views++</button>
<button @click="likes++">Likes++</button>
<div>
<p>Current state:</p>
<p>Subscribers: {{ subscribers }}</p>
<p>Views: {{ views }}</p>
<p>Likes: {{ likes }}</p>
</div>
</div>
</template>
In our example we have 2 sections. The top section uses the v-memo directive and the bottom section (current state) does not.
As we keep clicking the views++
and likes++
buttons the current state of views and likes is being changed in our DOM in the current state section. But we notice that no changes are made in the section using our v-memo directive.
As soon as we click our subscriber++
button we now notice that our views and likes in our v-memo directive section changes to the current state value.
Pretty useful when you have to control how a large application re-renders .
There is one current downside though. v-memo does not function in a v-for loop, so if we want to memoize something with a v-for, we have to put them on the same element.
v-memo is going to be rarely called upon but it’s pretty useful to know there a directive that does what it does. It is super useful for optimizations.