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

Rate this content
Bookmark

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.

22 min
15 May, 2023

Video Summary and Transcription

This talk compares Rev and Reactive in Vue 3, exploring reactivity and their limitations. It discusses the use of watchers, identity issues, and migration strategies. The talk also highlights the benefits of using the Ref function for better reactivity and the recommended pattern of grouping Refs. Opinions from the Vue community are shared, with a majority preferring Ref over Reactive.

Available in Español

1. Introduction to Rev vs. Reactive in Vue 3

Short description:

Welcome to my talk, Rev vs. Reactive. I will explain how you can choose whether to use Rev, Reactive, or both. We will explore the basics of reactivity in Vue 3 and compare Reactive and Rev. Finally, I will discuss the opinions from the Vue community and share a recommended pattern for grouping Rev and Reactive.

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 Hoffman. 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 de-structuring 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.

2. Reactivity in Vue 3

Short description:

Reactivity in Vue 3 is crucial for keeping the model and Vue in sync. JavaScript is not reactive by default, so Vue uses proxies and getter-setters to implement reactivity. The reactive function returns a reactive proxy object based on the provided object. It's similar to vue.observable in Vue 2 and creates deeply reactive state.

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 the 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.

3. Limitations of Reactive in Vue 3

Short description:

We define a watcher that correctly outputs the initial state. Limitations of reactive include exclusively working on object types and not having the same identity as the original object. Destructuring a reactive object property into a local variable disconnects reactivity. Vue provides a solution with the two refs function. Another problem arises when reassigning a reactive value, causing reactivity connection to be lost.

And we pass in the object, and 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 object property into a local variable. We have a state with reactive count 0. 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 two refs function. We have, again, our state with count 0. We can import two refs from the Vue package. The two refs 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 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 0. 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.

4. Watcher, Identity, and Migration

Short description:

Be careful with the watcher not firing and the different identity between the proxy and the original object. Passing a property into a function can cause problems. Reactive is a good choice for composition API migration. Copy everything from data into reactive to migrate components.

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 0. 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 0 and name myCounter. 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.

5. Ref Function and Reactivity

Short description:

Ref addresses the limitations of reactive and can hold any value type, including primitive values and complex data types. To create a reactive variable using ref, we import ref from the view package and pass a primitive or object as the initial value. Reading and modifying the reactive variable requires accessing the value property. Internally, ref creates a new object with a getter and a setter, utilizing the same track and trigger functions as reactive. Ref also uses reactive under the hood for object types. However, destructuring a ref or reassigning count.value disconnects reactivity.

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 a primitive like here into 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.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.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 an 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 0. And if we 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.

6. Reactivity and Refs in Vue 3

Short description:

To maintain reactivity when working with refs, you can group them in a plain JavaScript object. Passing refs into functions preserves reactivity and is useful for extracting logic into composables. Refs can be replaced with new object references without losing reactivity. Vue automatically unwraps refs in templates and watcher dependencies. The unwrap utility function correctly unwraps refs, making it easier to work with reactive variables.

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 it's 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 account 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 account with the ref zero. And the first argument of the watch function with 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 unwrap 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 unwrap 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 unwrap on our non-reactive variable name, it works also and locks the correct result.

7. Utilizing Refs and Reactives in Vue.js

Short description:

unwrap is a sugar function that checks if a variable is a ref and calls .value if it is. Ref can be used with any value, but values are accessed differently in script and template. Ref objects can be reassigned and passed across functions without losing reactivity. My preference is ref because it's easier to identify reactive values. Grouping refs inside a reactive object is a recommended pattern for better organization and easier handling.

And that works because unwrap is a sugar function for it checks if the variable is a ref. And if it is a ref, it returns, it calls count.value. Otherwise it just returns the value itself. If you're using VSCode 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 hit, 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 view tools 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 it's 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 an 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.

8. Opinions from the Vue Community

Short description:

Opinions from the Vue community show that more than 60% prefer using ref, while 8% use reactive and 22% use both. Michael Thiessen wrote an in-depth article about ref versus reactive, summarizing the opinions of famous people from the Vue community. The recommendation is to use ref by default and reactive when grouping variables. Both ref and reactive are powerful tools in Vue 3, so choose the one you prefer and maintain consistency in your code.

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 PNA, Daniel Roux, the leader of the Nux 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.

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

Vue.js London Live 2021Vue.js London Live 2021
34 min
Everything Beyond State Management in Stores with Pinia
Top Content
When we think about Vuex, Pinia, or stores in general we often think about state management and the Flux patterns but not only do stores not always follow the Flux pattern, there is so much more about stores that make them worth using! Plugins, Devtools, server-side rendering, TypeScript integrations... Let's dive into everything beyond state management with Pinia with practical examples about plugins and Devtools to get the most out of your stores.
Vue.js London Live 2021Vue.js London Live 2021
20 min
One Year Into Vue 3
Top Content
Vue 3 may still sound new to many users, but it's actually been released for over a year already. How did Vue 3 evolve during this period? Why did it take so long for the ecosystem to catch up? What did we learn from this process? What's coming next? We will discuss these questions in this talk!
Vue.js London Live 2021Vue.js London Live 2021
8 min
Utilising Rust from Vue with WebAssembly
Top Content
Rust is a new language for writing high-performance code, that can be compiled to WebAssembly, and run within the browser. In this talk you will be taken through how you can integrate Rust, within a Vue application, in a way that's painless and easy. With examples on how to interact with Rust from JavaScript, and some of the gotchas to be aware of.
Vue.js London Live 2021Vue.js London Live 2021
24 min
Local State and Server Cache: Finding a Balance
Top Content
How many times did you implement the same flow in your application: check, if data is already fetched from the server, if yes - render the data, if not - fetch this data and then render it? I think I've done it more than ten times myself and I've seen the question about this flow more than fifty times. Unfortunately, our go-to state management library, Vuex, doesn't provide any solution for this.For GraphQL-based application, there was an alternative to use Apollo client that provided tools for working with the cache. But what if you use REST? Luckily, now we have a Vue alternative to a react-query library that provides a nice solution for working with server cache. In this talk, I will explain the distinction between local application state and local server cache and do some live coding to show how to work with the latter.

Workshops on related topic

Vue.js London Live 2021Vue.js London Live 2021
169 min
Vue3: Modern Frontend App Development
Top Content
Featured WorkshopFree
The Vue3 has been released in mid-2020. Besides many improvements and optimizations, the main feature of Vue3 brings is the Composition API – a new way to write and reuse reactive code. Let's learn more about how to use Composition API efficiently.

Besides core Vue3 features we'll explain examples of how to use popular libraries with Vue3.

Table of contents:
- Introduction to Vue3
- Composition API
- Core libraries
- Vue3 ecosystem

Prerequisites:
IDE of choice (Inellij or VSC) installed
Nodejs + NPM
Vue.js London Live 2021Vue.js London Live 2021
117 min
Using Nitro – Building an App with the Latest Nuxt Rendering Engine
Top Content
Workshop
We'll build a Nuxt project together from scratch using Nitro, the new Nuxt rendering engine, and Nuxt Bridge. We'll explore some of the ways that you can use and deploy Nitro, whilst building a application together with some of the real-world constraints you'd face when deploying an app for your enterprise. Along the way, fire your questions at me and I'll do my best to answer them.
GraphQL Galaxy 2021GraphQL Galaxy 2021
48 min
Building GraphQL APIs on top of Ethereum with The Graph
WorkshopFree
The Graph is an indexing protocol for querying networks like Ethereum, IPFS, and other blockchains. Anyone can build and publish open APIs, called subgraphs, making data easily accessible.

In this workshop you’ll learn how to build a subgraph that indexes NFT blockchain data from the Foundation smart contract. We’ll deploy the API, and learn how to perform queries to retrieve data using various types of data access patterns, implementing filters and sorting.

By the end of the workshop, you should understand how to build and deploy performant APIs to The Graph to index data from any smart contract deployed to Ethereum.
React Summit 2022React Summit 2022
147 min
Hands-on with AG Grid's React Data Grid
WorkshopFree
Get started with AG Grid React Data Grid with a hands-on tutorial from the core team that will take you through the steps of creating your first grid, including how to configure the grid with simple properties and custom components. AG Grid community edition is completely free to use in commercial applications, so you'll learn a powerful tool that you can immediately add to your projects. You'll also discover how to load data into the grid and different ways to add custom rendering to the grid. By the end of the workshop, you will have created an AG Grid React Data Grid and customized with functional React components.- Getting started and installing AG Grid- Configuring sorting, filtering, pagination- Loading data into the grid- The grid API- Using hooks and functional components with AG Grid- Capabilities of the free community edition of AG Grid- Customizing the grid with React Components
JSNation 2022JSNation 2022
141 min
Going on an adventure with Nuxt 3, Motion UI and Azure
WorkshopFree
We love easily created and deployed web applications! So, let’s see what a very current tech stack like Nuxt 3, Motion UI and Azure Static Web Apps can do for us. It could very well be a golden trio in modern day web development. Or it could be a fire pit of bugs and errors. Either way it will be a learning adventure for us all. Nuxt 3 has been released just a few months ago, and we cannot wait any longer to explore its new features like its acceptance of Vue 3 and the Nitro Engine. We add a bit of pizzazz to our application with the Sass library Motion UI, because static design is out, and animations are in again.Our driving power of the stack will be Azure. Azure static web apps are new, close to production and a nifty and quick way for developers to deploy their websites. So of course, we must try this out.With some sprinkled Azure Functions on top, we will explore what web development in 2022 can do.
Vue.js London 2023Vue.js London 2023
137 min
TresJS create 3D experiences declaratively with Vue Components
Workshop
- Intro 3D - Intro WebGL- ThreeJS- Why TresJS- Installation or Stackblitz setup - Core Basics- Setting up the Canvas- Scene- Camera- Adding an object- Geometries- Arguments- Props- Slots- The Loop- UseRenderLoop composable- Before and After rendering callbacks- Basic Animations- Materials- Basic Material- Normal Material- Toon Material- Lambert Material- Standard and Physical Material- Metalness, roughness - Lights- AmbientLight- DirectionalLight- PointLights- Shadows- Textures- Loading textures with useTextures- Tips and tricks- Misc- Orbit Controls- Loading models with Cientos- Debugging your scene- Performance