Ref() vs. Reactive(): What to Choose Using Vue 3 Composition API?


There are two approaches to add a reactive state to Vue components using the Composition API. As a result, you must choose whether to utilize reactive(), ref(), or both. I'll guide you in making the best decision.


Hi vue lovers around the world. Welcome to my talk, Rev vs. Reactive. What to choose using vue 3's composition api. My name is Michael Hoffmann, I'm a senior front-end developer and freelancer from Munich, Germany. I'm focused on vue.js and I run a weekly vue newsletter and I'm very active on Twitter, so make sure to say hi there. Let's get started. I love vue 3's composition api, but it provides two approaches to adding reactive state to vue components. You can either choose Rev or Reactive. It can be cumbersome to use.value everywhere when using Revs. On the other hand, you can easily lose reactivity when destructuring reactive objects. So in this talk, I will explain to you how you can choose whether to use Rev, Reactive or both of them. First, I need to explain some basics of reactivity in vue 3. Then we take a detailed look at Reactive and Rev. We do a comparison between both of them and in the end, there's a conclusion where I will talk about my opinion and the opinions from the vue community and I will show you a recommended pattern how you can group Rev and Reactive. Let's get started with reactivity in vue 3. What is reactivity and why does vue need it? A reactivity system is a mechanism that automatically keeps in sync a data source, our model, with a data representation, our vue. If the model changes, the vue is re-rendered to reflect the changes. And this is a crucial mechanism for any web framework. But javascript is not reactive per default. Let's take a look at a code example. Here we have a variable price with the value 10 and a variable quantity with the value 2. We calculate total by multiplying price and quantity. If we log total, we get 20 as expected. But what happens if we now assign a new value to price, in this example 20. And if we now log the result, total is still 20. In a reactivity system, we would expect that total is updated each time price or quantity is changed. But javascript usually doesn't work like this. That's the reason why the vue framework had to implement another mechanism to track the reading and writing of local variables. How vue implements reactivity? It works by intercepting the reading and writing of object properties. vue 3 therefore uses proxies for reactive objects and getter setters for refs. Let's take a look at the simplified code examples, which ignores a lot of edge cases and details. We have a reactive function that receives an object. Inside the function, we return a new proxy object based on the given object passed into the function as argument. The getter of the proxy object receives a target map, which stores effects, a short form for side effects. And these are functions that modify the application state. The track function is used to check whether there is a currently running effect. And then the getter returns the effect in the target map for the given key. The setter also receives the target map, the key, and the value of our effect. The trigger function looks up the subscriber effects for the property and invokes them. You don't have to understand all the details that are going on in this code example. But what you should remember is that vue 3 uses objects to implement the reactivity. Just for your information, vue 2 used object getter setters exclusively due to browser limitations. Let's now take a look at the reactive function. It returns a reactive proxy of the provided object. We can import reactive from the vue package and then call the function and pass in any object like in our example count zero. This is the equivalent of vue.observable, which was available in vue version 2. The state created with the reactive function is deeply reactive by default. So in this example, we define a new state calling the reactive function. And we pass in an object that contains a count zero and an additional nested object that also contains count zero. We define a watcher that watches our state and locks the state each time it changes. So it will correctly output the initial state. But what happens if we now call an increment method that increments our nested count using state.nested.count? And if we update this nested value, the watcher is also triggered because it's deeply reactive by default. Let's take a look at some limitations of reactive. The reactive api has two limitations. The first one is it works exclusively on object types like objects, arrays, or collection types such as map or set. And it doesn't work with primitive types like string, number, or Boolean. The second limitation is that the return proxy object from reactive doesn't have the same identity as the original object. So we define a plain javascript object. We call the reactive function and pass in the plain javascript object. And the reactive function returns a new proxy object. If we now do a comparison using the strict equality operator between the proxy object and the plain javascript object, the result will be false, which means that they don't have the same identity. We have a problem due to the different identity between the proxy and the original object. And it occurs if you try to destructure a reactive's object property into a local variable. We have a state with reactive count zero. And if you now try to destructure count into a local variable, this disconnects the reactivity from state.count. So if you now try to increment count, this doesn't affect the original state, because count is now a plain number and won't trigger any watchers, for example. So you need to be careful there. Luckily, vue provides a solution for that. And that's the toRefs function. We have, again, our state with count zero. We can import toRefs from the vue package. The toRefs function accepts an argument, and we can pass in our reactive proxy object. And then we can destructure its properties. And the destructure property is a ref, and it maintains the reactivity. So be careful if you try to destructure reactive objects. There's a second problem due to the different identities. And it appears if you try to reassign a reactive value. So we have our state with count zero. We define a watcher for the state, which locks our initial state. But if you now try to reassign a completely new reactive object to our state variable, this doesn't work, because the reference is no longer being tracked, and our reactivity connection is lost. So the watcher won't fire. So be careful here. This can also cause tricky problems in your application. There's a third problem with the different identity between the proxy and the original object using the reactive function. And it happens if you try to pass a property into a function. Let's take a look at our state with count zero. And we now want to pass the count accessed by state.count in a useful function. The useful function receives the count, but the count is here a plain number and not reactive anymore. So be careful here. This can also cause tricky bugs in your code. But reactive is a good choice for composition api migration, because reactive works very similarly to the reactive properties inside of the data field. This is the code of our options api component with the data field that contains an object with count zero and name my counter. We can simply copy everything from data into reactive to migrate this component to composition api. So this is the same component using composition api. And as you can see, you can copy paste the same object into the reactive function. And that's quite handy to do a composition api migration. Now let's take a look at the ref function. And ref addresses the limitations of reactive. Ref is not limited to object types, but can hold any value type. So we can use it for primitive values like string, number, Boolean. But it can also store complex data type like objects, arrays, or even DOM elements. We can import ref from the view package. And then we can create a reactive variable using the ref function. And we can pass in a primitive like here in the number zero or an object like in this example count zero. To read and write the reactive variables created with ref, we need to call the dot value property. So we have again our count with ref zero. If we now log count, we can see that it returns an object with value zero. So to access the value, we need to call count dot value. To modify the reactive variable, we also need to call count. To modify the reactive variable, we also need to call dot value. In this example, we want to set the count to two. So we have to call count dot value and set its value to two. If you log the result, we can see that the value is correctly updated to two. Let's take a look at the internals of ref. Because maybe you ask yourself the question, how can ref hold primitive values after we have learned that view's reactivity system is based on intercepting the reading and writing of objects and a primitive value isn't the object? So let's take a look at the simplified code for demonstration purposes that shows how ref works internally. So we have the function ref that receives a value, in this case, any primitive like string, Boolean, or number. And inside the ref function, a new object is created that is also returned from here. And inside the object, we have a getter and a setter. And they both use the same track and trigger functions that we already discussed in the reactivity section. What's quite interesting is that ref uses reactive under the hood if you pass in object types like arrays or objects. So you can, in a simplified way, calling ref with an object is nearly the same as calling ref with calling reactive and an object. Let's talk about destructuring a ref, because the reactivity is also lost if you try to destructure a reactive object created with ref. So we have our count with ref zero. And if you now try to destructure value from count, this disconnects the reactivity and the count destructured variable would be a plain number in this example. Same happens if you reassign count.value to a new variable, in this example, count value. This also disconnects the reactivity, and count value would also be a plain number. So you also need to be careful here. A workaround would be to group your refs in a plain javascript object. So here we have state, which is a plain javascript object containing a property with the value ref one and another property name containing a ref with Michael. And now you can destructure count and name from the state object, and both will be still reactive because both are refs. Let's talk about passing ref into functions, because you can do that without losing reactivity. We have again our state example with a count ref one and a name ref Michael. And we now want to pass the count into use foo. Use foo receives one argument count, which is a ref and is fully reactive. So if you remember, this is now fully reactive in comparison to reactive, to using reactive where the reactivity was lost in the same example. And this capability is quite important, as it is frequently used when you extract your logic into composables. Let's now try to replace a ref object with a new object reference. In this example, we have defined a new reactive variable state by calling ref with an object containing count one and the name Michael. Now we want to reassign a completely new object. In this example, we call state.value and pass and reference a new object with count two and name Chris. And this works using ref, and the state is still reactive. So this is a big advantage compared to using reactive. In this chapter, we take a look at unwrapping refs, because vue helps us to unwrap refs without calling.value everywhere. First, vue automatically unwraps a ref when you call it in the template. So here we have inside the script setup our count with ref zero. And in the template, we don't need to call count.value, because vue automatically unwraps our ref here. The same is for watcher dependencies. We have our count with ref zero. And the first argument of the watch function is the watcher dependency. And here we don't need to call.value, because vue automatically unwraps the ref for us. vue also provides a handy utility function called unref that is especially useful if our value could be a ref. So here we have two variables, count, which is a reactive variable created with ref zero, and a local variable name that is assigned to the string Michael. We now import unref from the vue package and call it on our count. If we lock the result, we can see that it correctly unwrapped the ref. If we now call unref on our non-reactive variable name, it works also and locks the correct result. And that works because unref is a sugar function for it checks if the variable is a ref. And if it is a ref, it calls count.value. Otherwise, it just returns the value itself. If you're using VS Code and using the Volar extension, you can enable that it automatically adds.value to refs. This is a setting you can enable. It's called autocomplete refs. It's disabled by default to reduce CPU usage. And you can see in this example, if you enter the name count, the extension automatically adds.value after the variable name, which can be quite handy. Now let's do a comparison between reactive and ref. Ref scores as it can be used with any value in comparison to reactive that can only be used on object types. But there's a downside using ref, and that is because values are accessed differently in script and template. So this is a plus point for reactive. Because using ref inside the script tab, you need to call.value. But vue automatically unwraps the ref in the template, so you don't need to call.value there. Ref objects can be reassigned, which is a plus point for ref. Ref also scores because references can be passed across functions without losing reactivity. We also saw that reactive loses reactivity if we try to destructure object properties into local variables. But there's an advantage using reactive if you try to migrate to composition api, because it's similar to vue 2's data object. Let's come to the conclusion. My opinion, I prefer ref. And what I like most about ref is that you know that it's a reactive value if you see that its property is accessed via.value. And it's not that easy if objects are created with reactive. So if you see this line of code in your application, you don't know if any object is a plain javascript object or if it is a reactive object. If you see this line inside your application, it's quite likely that any ref is a ref and behaves reactively. Let's talk about a recommended pattern, and that's grouping refs inside a reactive object. So we have two refs, loading and error, and we pass them into a reactive object, which is assigned to a local state variable. We can now watch the whole reactive object using watch effect. But we can also define watchers for the refs separately. And what's nice about that, if we update the ref, for example, setting the loading value to false, this triggers both watchers. And if you don't need the reactivity of the state object, you can also group it in a plain javascript object. Grouping refs results in a single object, which is easier to handle, keeps your code organized, and at a glance, you can see that the grouped refs belong together and are somehow related. Let's talk about opinions from the vue community. I asked my Twitter followers if they are using ref or reactive, and more than 60% are using ref, 8% are using reactive, and 22% are using both, which is quite nice. And you can see that ref is the winner here. The amazing Michael Thiessen also wrote a brilliant in-depth article about ref versus reactive, and he collected the opinions of famous people from the vue community, like Eduardo, the creator of PNIA, Daniel Rowe, the leader of the Nuxt team, Matt from LearnVue, and many more. And summarized, they all use ref by default and reactive when they need to group things. So should you now use ref or reactive? My recommendation is to use ref by default and reactive when you need to group things. The vue community has the same opinion, but it's totally fine if you decide to use reactive by default. Ref and reactive are both very powerful tools to create reactive variables in vue 3. You can use both of them without any technical drawbacks. Just pick the one you like and try to stay consistent in how you write your code. Thanks for listening, and I'm happy to answer your questions.
23 min
15 May, 2023

Check out more articles and videos

We constantly think of articles and videos that might spark Git people interest / skill us up or help building a stellar career

Workshops on related topic