Computer scienceFrontendVue.jsVue 3 SyntaxVue ComponentsVue Advanced Components

Reactive

4 minutes read

In Vue 3, the Composition API introduces a new approach to organizing and managing logic within Vue components. One of the key concepts of this approach is reactivity, allowing components to automatically update UI when the state changes. To facilitate this reactivity, Vue provides the reactive function, which you'll learn about in this topic. Let's explore what it is, when and why it's used, and how it differs from the similar ref function.

What is reactive?

The reactive function is a method offered by Vue's Composition API to create reactive objects. Essentially, it transforms a regular JS object into a reactive one. When you alter any property of a reactive object, Vue tracks these changes and automatically updates the DOM. This simplifies the management of complex state, as you can group related data together, and Vue will efficiently update the component whenever any part of the state changes.

You can start using it by importing it from Vue and passing in any object that you want to make reactive:

<script setup>
import { reactive } from 'vue';

const ninja = reactive({
  name: 'Michelangelo',
  eyeMask: 'orange',
  weapons: 'dual nunchaku',
  isYoungest: true,
  traits: ['optimistic', 'funny', 'quick-witted']
});

</script>

If you've already worked with the ref function, you probably recall that it can accept any data structure. However, when it comes to reactive, you can only pass objects. This is one of the key differences between these two methods.

Another distinction is that you don't need to use the .value syntax with reactive, and you can directly access the object's properties. This is a significant advantage and reduces the need for extensive coding. Try console logging the name property right below our object to test it:

console.log(ninja.name);
// outputs 'Michelangelo'

Updating reactive object

Now that you have your reactive object, you might be wondering how to display it in the template and update when necessary. Let's start by fleshing out our template. It should contain the name inside the h1 tags and traits in the form of an ordered list. To access the properties, you just need to use interpolation (double curly braces), and the list itself can be displayed using v-for directive. Don't worry if you're not familiar with it yet, just think of it as of a simple for-loop: what it does is iterating over the traits array and showing each item. Here's how it looks like:

<template>
  <h1>{{ ninja.name }}</h1>
  <h4>Personal traits:</h4>
  <ol>
    <li v-for="trait in ninja.traits" :key="trait">
      {{ trait }}
    </li>
  </ol>
</template>

Michelangelo, the ninja turtle, is known as Mikey among his brothers. We also forgot to mention that he is energetic. Let's create a setTimeout() function that will wait for 3 seconds and then change the name to Mikey and add a new item to the traits array:

<script setup>
import { reactive } from 'vue';

const ninja = reactive({
  name: 'Michelangelo',
  eyeMask: 'orange',
  weapons: 'dual nunchaku',
  isYoungest: true,
  traits: ['optimistic', 'funny', 'quick-witted']
});

setTimeout(() => {
  ninja.name = 'Mikey';
  ninja.traits.push('energetic');
}, 3000)

</script>

Inside the setTimeout() you directly accessed the name property of the ninja object and assigned a new name — Mikey. Additionally, you added "energetic" to the traits array using the push() method. As you can see, with reactive, you can change primitive values like strings, as well as arrays.

The result:

reactive example

Awesome! Our app looks pretty reactive!

The reactive function tracks nested properties as well. If you want to monitor changes on the root level only, consider using shallowReactive() instead.

Ref vs reactive

The primary difference between ref and reactive is how they handle reactivity. The ref is for primitive values and wraps them in an object to make them reactive, which means you need to access the value using .value. On the other hand, reactive doesn't wrap objects, so you can access the properties directly.

Another difference is that ref is more flexible because it can be used with both primitives and objects, while reactive can only be used with objects. However, when using ref with objects, you still need to access properties using .value, which can be less convenient.

To sum up, if you're dealing with a single primitive value, ref is the way to go. If you're dealing with an object or an array and your application is pretty big, reactive is more appropriate.

Conclusion

The reactive function is a critical part of the Composition API, enabling you to create reactive objects that automatically update the DOM when their properties change. This feature simplifies the management of complex state, allowing for efficient and streamlined coding. It's important to understand the distinctions between reactive and ref. While both functions facilitate reactivity, they differ in their usage and flexibility. Theref is ideal for handling primitive values and offers greater flexibility as it can be used with both primitives and objects. The reactive, on the other hand, is best suited for objects and arrays, particularly in larger applications, due to its direct property access and efficient handling of complex states.

How did you like the theory?
Report a typo