← Back to all snippets
JAVASCRIPT

Optimizing Re-renders with `v-memo`

Improve Vue 3 application performance by using the `v-memo` directive to memoize template sub-trees, preventing unnecessary re-renders when dependencies haven't changed.

// MemoComponent.vue
<template>
  <div>
    <h1>v-memo Example</h1>
    <p>This component renders a list of {{ items.length }} items.</p>
    <p>Number of active users: {{ activeUsers }}</p>

    <!-- The entire div below will only re-render if `activeUsers` changes -->
    <div v-memo="[activeUsers]" class="memoized-block">
      <h2>Memoized Block</h2>
      <p>This block's content is costly to render.</p>
      <p>Active Users (memoized): {{ activeUsers }}</p>
      <p>Calculated expensive value: {{ calculateExpensiveValue(activeUsers) }}</p>
      <p>Last memoized at: {{ new Date().toLocaleTimeString() }}</p>
      <button @click="incrementActiveUsers">Increment Active Users (inside memo)</button>
    </div>

    <!-- This block will re-render on any prop/state change -->
    <div class="non-memoized-block">
      <h2>Non-Memoized Block</h2>
      <p>This block always re-renders.</p>
      <p>Current time: {{ new Date().toLocaleTimeString() }}</p>
      <button @click="addItem">Add Item (triggers full re-render)</button>
    </div>
  </div>
</template>

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

const items = ref(['Item 1', 'Item 2']);
const activeUsers = ref(10);

const addItem = () => {
  items.value.push(`Item ${items.value.length + 1}`);
  console.log('Items updated, full component re-render expected.');
};

const incrementActiveUsers = () => {
  activeUsers.value++;
  console.log('Active users updated, v-memo block re-render expected.');
};

const calculateExpensiveValue = (num) => {
  // Simulate an expensive calculation
  console.log('Calculating expensive value...');
  let result = 0;
  for (let i = 0; i < 1000000; i++) {
    result += Math.sqrt(i) * num;
  }
  return result.toFixed(2);
};
</script>

<style scoped>
.memoized-block {
  border: 1px solid blue;
  padding: 10px;
  margin-top: 20px;
}
.non-memoized-block {
  border: 1px solid red;
  padding: 10px;
  margin-top: 20px;
}
</style>
How it works: This snippet demonstrates the `v-memo` directive in Vue 3, used for optimizing re-renders of static or conditionally static template parts. The `v-memo="[activeUsers]"` directive on the first `div` means that this entire block will only re-render if the value of `activeUsers` changes. If other reactive data (like `items`) changes, the rest of the component will update, but the memoized block (and its potentially expensive calculations) will be skipped, improving performance. The `calculateExpensiveValue` function illustrates a scenario where memoization prevents unnecessary computations.

Need help integrating this into your project?

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

Hire DigitalCodeLabs