Open In App

Vue Render Optimization with v-once and v-memo

Rendering speed is crucial for a good user experience in modern apps. Out of all ways, one extremely easy way to optimize rendering is by only re-rendering what needs to be. While Vue re-renders components when their data changes this can lead to inefficiencies. v-once and v-memo directives offer a solution by allowing control over re-rendering, improving performance.

How v-once and v-memo Optimize the Vue Render?

v-once and v-memo are directives used for optimizing components with reactive data that:

A v-memo with no dependencies works like v-once, meaning it only renders the element or component once.

Using the v-once for optimization

The v-once directive ensures that the element or component it's applied to is rendered only once during the initial render cycle. Subsequent updates to reactive data within that element or component will not trigger re-rendering.

Example: The below code implements the v-once directive to render the VueJS code.

<template>
    <div style="text-align: center">
        <h2>
            The text below input field will 
            not change as it<br /> is rendered 
            using v-once directive.
        </h2>
        <input type="text" v-model="reply" />
        <h3 v-once>{{ reply }}</h3>
    </div>
</template>

<script>
    import { ref } from 'vue';
    export default {
        setup() {
            const reply = ref("Reply");
            return {
                reply
            };
        }
    };
</script>

Output:
fosiGIF

Key Features of v-once:

Using the v-memo for optimization

The v-memo directive provides more granular control over re-rendering. It allows you to define an array of dependencies. The element or component wrapped with v-memo will only re-render if one or more of the values in the dependency array change.

Example: The below code implements the v-memo directive to optimize the Vue rendering.

<template>
    <div style="text-align: center">
        <h2>
            The text below input field will be 
            replaced with the entered <br />text 
            as it is rendered using v-memo directive.
        </h2>
        <input type="text" v-model="reply" />
        <h3 v-memo=[reply]>{{ reply }}</h3>
    </div>
</template>

<script>
    import { ref } from 'vue';
    export default {
        setup() {
            const reply = ref("Reply");
            return {
                reply
            };
        }
    };
</script>

Output:

fosiGIF

Key Features of v-memo:

Article Tags :