DEV Community

Cover image for Using shallowRef in Vue to improve performance
Jakub Andrzejewski
Jakub Andrzejewski

Posted on

Using shallowRef in Vue to improve performance

Handling large data structures in frontend applications is not easy. However, I recently learned about a great feature of Vue called shallowRef which is a great utility that could help improve performance of your website if you are dealing with huge data structures like nested objects or arrays.

So amazing that the framework author already thought about such useful feature and implement it directly in the framework instead of a need to use third party package or write such functionality from scratch.

In this article, I decided to write about it so that you can start using it in your app as well!

Enjoy!

πŸ€” What is a Vue shallowRef?

Unlike ref(), the inner value of a shallow ref is stored and exposed as-is, and will not be made deeply reactive. Only the .value access is reactive.

<script setup lang="ts">
import { shallowRef } from 'vue'

const state = shallowRef({
  count: 0,
})
</script>

<template>
  <span>Count: {{ state.count }}</span>
</template>
Enter fullscreen mode Exit fullscreen mode

For this example, shallowRef will work the same way as the normal ref. The difference will come into place when we will try to update it. Let's see how we can achieve that in the next section.

🟒 Using shallowRef to improve performance

shallowRef() is typically used for performance optimizations of large data structures, or integration with external state management systems. Let's take a look at the following example that is related to the previous component example.

// does NOT trigger change
state.value.count = 2
Enter fullscreen mode Exit fullscreen mode

The reason for that is that once we have large data structures like nested objects or arrays, we can avoid triggering state change for the nested properties every time a property changes. This means also that the UI won't be updated if you update the property of shallowRef variable.

To change it in a way that will be reflected in the UI, we would need to replace the whole state object like so:

// does trigger change
state.value = { count: 2 }
Enter fullscreen mode Exit fullscreen mode

By using shallowRef in case of large data structures, we can improve performance of our website significantly by avoiding not needed state and UI updates

πŸ“– Learn more

If you would like to learn more about Vue, Nuxt, JavaScript or other useful technologies, checkout VueSchool by clicking this link or by clicking the image below:

Vue School Link

It covers most important concepts while building modern Vue or Nuxt applications that can help you in your daily work or side projects πŸ˜‰

βœ… Summary

Well done! You have just learned how to use shallowRef to improve performance of your website.

Take care and see you next time!

And happy coding as always πŸ–₯️

Top comments (0)