Boost Vue 3 Performance with v‑memo: When and How to Use It
This article explains Vue 3’s v‑memo directive, how it conditionally skips component updates by tracking dependency arrays, and demonstrates its use to dramatically reduce rendering costs in large v‑for lists compared to traditional v‑if/v‑show approaches.
v-ifand v-show control whether an element is rendered, but the real performance bottleneck often lies in unnecessary re‑rendering.
To address this, Vue 3 introduces a dedicated directive— v-memo.
What is v-memo ?
v-memois a directive that conditionally skips the update of an element or component. Its syntax is:
<div v-memo="[depA, depB]">
...
</div> v-memoreceives a dependency array; Vue will re‑render the div and its children only when at least one value in the array changes, otherwise the diff step is skipped.
When to use v-memo
v-memois not a replacement for v-if or v-show; it specifically solves tricky rendering‑performance problems.
The most classic and effective scenario is optimizing a very long v-for list. Imagine a list of 1,000 users, each with name and status (online/offline).
Version without v-memo:
If a user’s status changes, Vue theoretically needs to traverse the entire list, create new VNodes for every node, and run diff.
Version with v-memo:
<template>
<div v-for="user in users" :key="user.id" v-memo="[user.status]">
<p>{{ user.name }}</p>
<p :class="user.status === 'online' ? 'green' : 'grey'">
{{ user.status }}
</p>
</div>
</template>Note that the directive is written as v-memo="[user.status]".
When a particular user’s status changes, only the corresponding div ’s v-memo dependency changes, so only that div is re‑rendered. Vue skips updating the other 999 users.
With a single line of code, the update‑check cost drops from O(n) to O(1), updating only the changed item.
Comparison with v-once
v-onceis essentially a special case of v-memo; it is equivalent to v-memo="[]". Because the dependency array is empty, it never changes, and the component is permanently “frozen” after the first render.
The debate between v-if and v-show solves the “render or not” problem, but modern front‑end applications face a larger performance challenge: reducing the amount of updates rather than merely toggling visibility.
JavaScript
Provides JavaScript enthusiasts with tutorials and experience sharing on web front‑end technologies, including JavaScript, Node.js, Deno, Vue.js, React, Angular, HTML5, CSS3, and more.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
