Vue 3: Ref vs Reactive

Introduction to Vue 3 Reactivity

Vue 3's reactivity system is a core feature that keeps the data source, known as the model, synchronized with its representation in the view. This synchronization ensures that any change in the model is automatically reflected in the view, making it crucial for modern web frameworks. JavaScript, by itself, does not support reactivity, which is why Vue's approach is so significant. In Vue 3, reactivity is achieved through the use of refs and reactive objects, each serving distinct purposes.

The introduction of Vue 3 brought about the Composition API, which includes two primary methods for implementing reactive state: ref and reactive. Each method comes with its own set of functionalities and limitations, making it essential to understand when and how to use each one effectively.

Ref: Versatile and Simple

The ref function in Vue 3 is a powerful tool that addresses the limitations of the reactive function by offering a way to work with both primitive and complex data types. Unlike reactive, which is limited to objects, ref can hold strings, numbers, booleans, arrays, objects, and even DOM elements. This versatility makes ref particularly useful when dealing with a wide range of data types within a Vue application.

Using ref involves creating a reactive variable and accessing its value through the .value property. For example, to initialize a ref variable, you use ref(0) for a number or ref({count: 0}) for an object. To read or write to these variables, you must use .value, such as count.value.

Internally, ref works by creating an object with a getter and setter, using the same track and trigger functions that Vue's reactivity system employs for objects. This mechanism allows ref to maintain reactivity even with primitive values, which are not inherently objects.

Limitations and Considerations for Ref

One significant limitation of ref is that destructuring a ref variable disconnects its reactivity. When you destructure value from a ref-created object, the new variable becomes a plain value, losing its reactive capabilities. This can lead to unexpected behavior in applications if not handled carefully.

To overcome the inconvenience of using .value, especially in development environments like VSCode, the Volar extension can be configured to autocomplete .value for refs. This feature, though disabled by default to conserve CPU resources, can streamline the development process.

Reactive: Deep Reactivity for Objects

The reactive function in Vue 3 is designed to create deeply reactive objects, offering an alternative approach to reactivity. Unlike ref, which is versatile with data types, reactive is specifically tailored for objects, arrays, and collection types such as Map or Set. This makes it suitable for complex state management within applications.

Reactive uses proxies to intercept the reading and writing of object properties, a method that offers a more seamless integration when working with multiple object properties. This proxy-based system allows reactive to automatically track changes and trigger updates whenever the object's properties are accessed or modified.

However, reactive objects come with the caveat of losing reactivity when their properties are destructured. Additionally, the proxy object returned by reactive does not share the same identity as the original object, which can lead to complications when performing operations like comparisons or reassignment.

Choosing Between Ref and Reactive

The choice between ref and reactive largely depends on the specific requirements of your application. Ref is preferred when working with a mix of data types due to its flexibility and ease of use. It also allows for passing reactive references across functions without losing the reactivity, which is beneficial when extracting logic into composables.

Conversely, reactive is advantageous when managing complex objects and provides a more intuitive approach during composition API migration, as it closely resembles the data properties used in the options API. The decision to use one over the other should be guided by the application's needs and the developer's familiarity with the tools.

Grouping Refs for Enhanced Organization

One recommended pattern is grouping multiple refs within a reactive object. This approach combines the strengths of both ref and reactive by maintaining individual reactivity for each ref while organizing them into a single, easily manageable object. This pattern simplifies state management and improves code organization, ensuring that related refs are visibly connected.

By using this pattern, you can define watchers for the entire reactive object or for individual refs, providing flexibility in how state changes are monitored and handled. Updating a ref within the grouped object triggers the relevant watchers, maintaining a cohesive reactivity system.

Community Insights and Best Practices

The Vue community generally leans towards using ref by default, with reactive being employed when there's a need to group related data. This preference is reflected in community polls and articles by prominent Vue developers, who advocate for the use of ref due to its simplicity and versatility.

Regardless of the choice between ref and reactive, consistency in their usage is crucial. Both ref and reactive are powerful tools in Vue 3's arsenal, and their effective application can greatly enhance the reactivity and maintainability of Vue applications.

In summary, understanding the strengths and limitations of ref and reactive is key to leveraging Vue 3's reactivity system effectively. By choosing the right tool for the task and employing best practices, developers can create responsive and efficient Vue applications.

Watch full talk with demos and examples:

Rate this content
Bookmark

From Author:

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.

This talk has been presented at Vue.js London 2023, check out the latest edition of this JavaScript Conference.

Watch video on a separate page

FAQ

Vue 3 handles reactivity for primitive values through the Ref function, which wraps the primitive in an object with getters and setters to facilitate reactivity.

A recommended pattern is to group Refs inside a Reactive object, which allows for easier management of related reactive properties and ensures that updates to individual Refs trigger reactivity as expected.

Ref is generally preferred because it explicitly shows reactivity with the '.value' syntax, works with any type of value, and maintains reactivity across reassignments and function passes. It's also easier to see at a glance that a value is reactive.

While Ref and Reactive can both be used to create reactive variables, they are not completely interchangeable due to their different handling of reactivity and types of values they support. Ref is versatile with all value types, but Reactive is specifically efficient for reactive object properties.

Ref can hold any type of value and requires accessing values with '.value', suitable for both primitives and objects. Reactive is used primarily for objects and does not use '.value' to access properties but can lose reactivity when destructuring or reassigning objects.

The Reactive function in Vue 3 only works on object types (like objects, arrays, or collections such as Map or Set) and the returned proxy object from Reactive does not have the same identity as the original object, which can lead to issues when destructuring or reassigning.

In Vue 3's composition API, you can add reactive state using either 'Ref' or 'Reactive'.

Michael Hoffmann
Michael Hoffmann
22 min
15 May, 2023

Comments

Sign in or register to post your comment.
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.

1. Introduction to Rev vs. Reactive in Vue 3

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.

2. Reactivity in Vue 3

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.

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

Everything Beyond State Management in Stores with Pinia
Vue.js London Live 2021Vue.js London Live 2021
34 min
Everything Beyond State Management in Stores with Pinia
Top Content
State management is not limited to complex applications and transitioning to a store offers significant benefits. Pinia is a centralized state management solution compatible with Vue 2 and Vue 3, providing advanced devtools support and extensibility with plugins. The core API of Pinia is similar to Vuex, but with a less verbose version of stores and powerful plugins. Pinia allows for easy state inspection, error handling, and testing. It is recommended to create one file per store for better organization and Pinia offers a more efficient performance compared to V-rex.
Welcome to Nuxt 3
Vue.js London Live 2021Vue.js London Live 2021
29 min
Welcome to Nuxt 3
Top Content
Nux3 has made significant improvements in performance, output optimization, and serverless support. Nuxt Bridge brings the Nitro engine for enhanced performance and easier transition between Nuxt 2 and Nuxt Read. Nuxt 3 supports Webpack 5, Bytes, and Vue 3. NextLab has developed brand new websites using Docus technology. Nuxt.js is recommended for building apps faster and simpler, and Nuxt 2 should be used before migrating to Nuxt 3 for stability. DOCUS is a new project that combines Nuxt with additional features like content modules and an admin panel.
One Year Into Vue 3
Vue.js London Live 2021Vue.js London Live 2021
20 min
One Year Into Vue 3
Top Content
Vue 3 has seen significant adoption and improvements in performance, bundle size, architecture, and TypeScript integration. The ecosystem around Vue 3 is catching up, with new tools and frameworks being developed. The Vue.js.org documentation is undergoing a complete overhaul. PNIA is emerging as the go-to state management solution for Vue 3. The options API and composition API are both viable options in Vue 3, with the choice depending on factors such as complexity and familiarity with TypeScript. Vue 3 continues to support CDN installation and is recommended for new projects.
Utilising Rust from Vue with WebAssembly
Vue.js London Live 2021Vue.js London Live 2021
8 min
Utilising Rust from Vue with WebAssembly
Top Content
In this Talk, the speaker demonstrates how to use Rust with WebAssembly in a Vue.js project. They explain that WebAssembly is a binary format that allows for high-performance code and less memory usage in the browser. The speaker shows how to build a Rust example using the WasmPack tool and integrate it into a Vue template. They also demonstrate how to call Rust code from a Vue component and deploy the resulting package to npm for easy sharing and consumption.
Vue: Feature Updates
Vue.js London 2023Vue.js London 2023
44 min
Vue: Feature Updates
Top Content
Watch video: Vue: Feature Updates
The Talk discusses the recent feature updates in Vue 3.3, focusing on script setup and TypeScript support. It covers improvements in defining props using imported types and complex types support. The introduction of generic components and reworked signatures for defined components provides more flexibility and better type support. Other features include automatic inference of runtime props, improved define emits and defined slots, and experimental features like reactive props destructure and define model. The Talk also mentions future plans for Vue, including stabilizing suspense and enhancing computer invalidations.
Local State and Server Cache: Finding a Balance
Vue.js London Live 2021Vue.js London Live 2021
24 min
Local State and Server Cache: Finding a Balance
Top Content
This Talk discusses handling local state in software development, particularly when dealing with asynchronous behavior and API requests. It explores the challenges of managing global state and the need for actions when handling server data. The Talk also highlights the issue of fetching data not in Vuex and the challenges of keeping data up-to-date in Vuex. It mentions alternative tools like Apollo Client and React Query for handling local state. The Talk concludes with a discussion on GitLab going public and the celebration that followed.

Workshops on related topic

Vue3: Modern Frontend App Development
Vue.js London Live 2021Vue.js London Live 2021
169 min
Vue3: Modern Frontend App Development
Top Content
Featured WorkshopFree
Mikhail Kuznetsov
Mikhail Kuznetsov
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
Monitoring 101 for React Developers
React Summit US 2023React Summit US 2023
107 min
Monitoring 101 for React Developers
Top Content
WorkshopFree
Lazar Nikolov
Sarah Guthals
2 authors
If finding errors in your frontend project is like searching for a needle in a code haystack, then Sentry error monitoring can be your metal detector. Learn the basics of error monitoring with Sentry. Whether you are running a React, Angular, Vue, or just “vanilla” JavaScript, see how Sentry can help you find the who, what, when and where behind errors in your frontend project. 
Workshop level: Intermediate
Using Nitro – Building an App with the Latest Nuxt Rendering Engine
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
Daniel Roe
Daniel Roe
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.
Hands-on with AG Grid's React Data Grid
React Summit 2022React Summit 2022
147 min
Hands-on with AG Grid's React Data Grid
Top Content
WorkshopFree
Sean Landsman
Sean Landsman
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
Building GraphQL APIs on top of Ethereum with The Graph
GraphQL Galaxy 2021GraphQL Galaxy 2021
48 min
Building GraphQL APIs on top of Ethereum with The Graph
WorkshopFree
Nader Dabit
Nader Dabit
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.
Going on an adventure with Nuxt 3, Motion UI and Azure
JSNation 2022JSNation 2022
141 min
Going on an adventure with Nuxt 3, Motion UI and Azure
WorkshopFree
Melanie de Leeuw
Melanie de Leeuw
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.