March 13, 2024

Ref vs reactive in Vue 3 With Example

Ref vs reactive in Vue 3 With Example

With the release of Vue 3, new features like Ref and Reactive have been introduced to enhance the reactivity system.

What is Ref?

Ref is a feature in Vue 3 that allows you to declare reactive state within components. It’s useful for managing individual values like counters or input fields.

What is Reactive?

Reactive enables reactivity on JavaScript objects and arrays. It’s perfect for managing complex data structures within Vue components.

Why Understanding Ref vs Reactive Matters

Understanding the differences between Ref and Reactive is essential for effective Vue development. By mastering these concepts, you can build dynamic and responsive user interfaces in Vue 3.

Let’s dive in!

Ref in Vue 3

Ref in Vue 3 is a way to declare reactive state within components. It’s perfect for managing individual values such as numbers, strings, or booleans. To access the value stored in a Ref, you need to use the .value property inside the script. In the template you can access it directly without .value.

Example: Imagine we have a simple Vue component that displays a counter. We want this counter to increment when a button is clicked. Here’s how we can use Ref to achieve this:

<template>
<div>
<p>Counter: {{ counter }}</p>
<button @click="increment">Increment</button>
</div>
</template>
<script setup>
import { ref } from 'vue';
// Declare a ref for the counter
const counter = ref(0);
// Function to increment the counter
function increment() {
counter.value++;
}
</script>

In this example, we import the ref function from Vue and use it to declare a reactive variable counter initialized with the value 0. We then define a function increment that increments the counter value when called.

Now, whenever the “Increment” button is clicked, the counter value will increase, and the component will automatically re-render to reflect the updated value.

Key Points:

  • Ref is used to declare reactive state within Vue components.
  • It’s ideal for managing individual values like numbers or strings.
  • Changes to a Ref value are automatically tracked, triggering re-renders of the component when necessary.

Reactive in Vuejs 3?

Reactive in Vue 3 enables reactivity on plain JavaScript objects and arrays. It allows Vue to track changes to the properties or elements of these objects and arrays, ensuring that components automatically update when the data changes.

Example: Suppose we have a form component that collects user information, including their name, email, and age. We want to make this form reactive so that any changes made by the user are reflected in real-time. Here’s how we can achieve this using reactive

<template>
<div>
<label>Name:</label>
<input type="text" v-model="formData.name">
<label>Email:</label>
<input type="email" v-model="formData.email">
<label>Age:</label>
<input type="number" v-model="formData.age">
<p>User Information:</p>
<p>Name: {{ formData.name }}</p>
<p>Email: {{ formData.email }}</p>
<p>Age: {{ formData.age }}</p>
</div>
</template>
<script setup>
import { reactive } from 'vue';
// Declare a reactive object for form data
const formData = reactive({
name: '',
email: '',
age: null
});
</script>

In this example, we use the reactive function from Vue to create a reactive object called formData, which contains properties for the user’s name, email, and age. We bind input fields to these properties using v-model, allowing Vue to automatically update the formData object as the user types.

As a result, any changes made to the form inputs will be reflected in real-time in the paragraph elements below, demonstrating the reactivity of the formData object.

Key Points:

  • Reactive enables reactivity on JavaScript objects and arrays in Vue 3.
  • It allows Vue to track changes to the properties or elements of these objects and arrays.
  • Changes to reactive data automatically trigger updates to components that reference them.

Differences in Data Reactivity between Vue 2 vs Vue 3

In Vue 2, data reactivity is primarily achieved using the Options API, which relies on the data property within components to define reactive data. However, Vue 3 introduces the Composition API, which offers a more flexible and modular approach to organizing component logic, including data reactivity.

Differences in Vue 2:
  • In Vue 2, reactive data is defined within the data property of a component using plain JavaScript objects.
  • Vue 2 provides built-in reactivity for data properties, allowing components to automatically re-render when data changes.
  • Computed properties and watchers are commonly used in Vue 2 to perform reactive computations or respond to changes in data.
Differences in Vue 3:
  • Vue 3 introduces the Composition API, which allows developers to organize component logic into composable functions.
  • Instead of relying on the data property, reactive data can be created using the reactive function from Vue.
  • The Composition API promotes better code organization and reusability by allowing logic to be encapsulated within individual functions.

Vue 3 Ref vs Reactive

While both Ref and Reactive serve as essential tools for managing reactivity in Vue 3, they have distinct purposes and use cases.

Ref: Ref is used to declare reactive state within components. It’s ideal for managing individual values like numbers, strings, or booleans. Changes to a Ref value are automatically tracked, triggering re-renders of the component when necessary.

Reactive: Reactive enables reactivity on plain JavaScript objects and arrays. It’s perfect for managing complex data structures within Vue components. Vue tracks changes to the properties or elements of reactive objects and arrays, ensuring components update when the data changes.

When to Use Ref: Use Ref when you need to manage simple, individual values within your components. Examples include counters, input field values, or boolean flags.

When to Use Reactive: Use Reactive when you need to manage complex data structures like objects or arrays within your components. Examples include form data, lists of items, or nested data structures.

reactive() Use-Case A good use-case for reactive() is a group of primitives that belong together:

const person = reactive({
name: 'Albert',
age: 30,
isNinja: true,
});

the code above feels more logical than

const name = ref('Albert');
const age = ref(30);
const isNinja = ref(true);

Shallow Ref in Vue 3

In Vue 3, alongside Ref and Reactive, we have another reactivity utility called Shallow Ref. Shallow Ref is similar to Ref but with a subtle difference in how it handles nested objects or arrays.

What is Shallow Ref?

Shallow Ref, as the name suggests, provides reactivity to a single value, but it doesn’t recursively observe nested properties of the value. In other words, changes to deeply nested properties won’t trigger reactivity updates in components using Shallow Ref.

Example: Let’s illustrate the behavior of Shallow Ref with an example. Suppose we have a nested object representing a user profile with id, name, and address properties. We’ll create a Shallow Ref for this object and observe its behavior:

<template>
<div>
<p>User Profile:</p>
<p>ID: {{ userProfile.id }}</p>
<p>Name: {{ userProfile.name }}</p>
<p>Address: {{ userProfile.address }}</p>
<button @click="updateUserProfile">Update Profile</button>
</div>
</template>
<script setup>
import { shallowRef } from 'vue';
// Declare a shallow ref for the user profile
const userProfile = shallowRef({
id: 1,
name: 'John Doe',
address: {
city: 'Example City',
country: 'Example Country'
}
});
// Function to update the user profile
function updateUserProfile() {
userProfile.value.name = 'Jane Smith'; // This change will trigger reactivity
userProfile.value.address.city = 'New City'; // This change won't trigger reactivity
}
</script>

In this example, we create a Shallow Ref for the userProfile object, which includes nested properties for id, name, and address. When we update the name property of the userProfile, it will trigger reactivity as expected. However, when we update the city property of the address object, it won’t trigger reactivity because Shallow Ref doesn’t recursively observe nested properties.

Key Points:

  • Shallow Ref provides reactivity to a single value but doesn’t recursively observe nested properties.
  • Changes to deeply nested properties won’t trigger reactivity updates when using Shallow Ref.
  • Shallow Ref is useful when you only need reactivity at the top level of an object or array and don’t want to incur the performance cost of deep reactivity.

Conclusion

In this guide, we’ve explored three essential reactivity utilities in Vue 3: Ref, Reactive, and Shallow Ref. And ref vs reactive when to use both of them. Ref is ideal for managing individual values, while Reactive enables reactivity on complex data structures.

As you continue your Vue journey, consider how Ref, Reactive, and Shallow Ref can enhance your development workflow and contribute to the success of your projects. You can also read about Vue Teleport Component Happy coding!

References

Vue 3 Reactivity Documentation. Link