DEV Community

Timea Pentek
Timea Pentek

Posted on

Quick overview of reactivity in Vue3

In my opinion, one of Vue’s most powerful features is its reactivity system. Reactivity allows the framework to automatically update the UI when the information behind it changes. By default, Javascript is not naturally reactive, if nobody tells it, it won’t know that the state changed.

In Vue3 with the Composition API it is common to use ref() and reactive() to add reactivity to a variable/object. Under the hood, Vue converts the data into a proxy object, which enables Vue to perform dependency tracking and change-notification when properties are accessed or modified. In-depth blog about reactivity here: https://blog.logrocket.com/your-guide-to-reactivity-in-vue-js/ 

The most common ways in Vue Composition API to achieve reactive states are by using reactive() or ref().

reactive()

This function only works with objects, and it does not work with primitives. The returned value from reactive() is a Proxy of the original object. When implementing reactive() we can avoid using the ‘.value’ to retrieve the properties of the object, in contrast with the ref() function where we have to use ‘.value’. To access a property we can do so by using ‘object.key’ notation. 

The question is, however, if losing ‘.value’ is a benefit or not. I have seen many opinions that losing ‘.value’ can make it harder to track which line of code is triggering a reactive effect. This issue is not so noticeable with small projects, but it can become much more difficult to track reactive objects in a large project. In fact, Vue dropped the reactivity transform feature which got rid of the ‘.value’ when using ref() mainly for this reason.

In addition to this, reactive has a few limitations such as limited value types (only works with objects), can’t replace entire reactive objects because the reactivity connection to the first reference would get lost, and is not destructure-friendly because, again, reactivity connection would get lost.

Because of these limitations, Vue currently recommends using ref as the primary API to declare a reactive state. 

ref()

Ref works with any data type, including objects. To create a reactive value for primitives (boolean, string, number, etc) we can only use ref(). Whenever we want to access the current value of the reactive property we have to use ‘(name of the value/object).value’. You do not need to append the ‘.value’ when using the ref in the HTML template. With ref, if you are passing it an object you can completely replace it with another one, this is not possible with reactive.

Hopefully, with this quick overview you've gained a bit more clarity about the differences of the two.

Top comments (0)