Copied to Clipboard
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
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 }
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 π₯οΈ