👈 Return to blog

Reactivity: ref() vs reactive() 👊

Overview

Vue is based on the concept of reactivity just like React and Angular which makes the user experience better. There are two methods in Vue to declare the reactive state of an element: ref() and reactive() functions. In this article, we will discover the difference between these two functions and their use cases.


Let’s start! 🤙🏼


What is ref()?

ref() is function that takes an argument like parameter, and returns it wrapped within a ref object with a .value property. It is the recommended way to declare reactive state.

import { ref } from "vue";

const text = ref("Hello Vue!");

console.log(text); //{ value: "Hello Vue!" }
console.log(text.value); //"Hello Vue!"

For access to the value of the state, you must use .value property in a JavaScript template, but if you must render the state in a component template, the .value property is not necessary.

<script setup>
  import { ref } from "vue";

  const text = ref("Hello Vue!");
</script>

<h1>{{ text }}</h1>

Why ref()?

For understand the utility of ref() method it’s necessary know how Vue works under the hood. When it is used in a template and change the ref value, Vue detects the change immediately and update the DOM accordingly,this is made possible with a dependency-tracking based reactivity system. In Vanilla JavaScript, there is no way to tracks of value’s changes, but it is possible intercept with getter and setter methods, when is a on object.


What is reactive()?

reactive() API is another way to declare reactive state and makes an object itself reactive.

reactive() API create a JavaScript Proxies and Vue intercepts all mutations and access of all properties.

import { reactive } from "vue";

const state = reactive({ count: 0 });

Limitations of reactive()

As said previously, ref() is raccomended way to declare reactive state, because reactive() API has some limitations:

  1. Can’t use primitive values: it only works with objects types.

  2. Cannot replace entire object: Vue’s reactivity monitor only works through properties access. This means that the declared object must remain the same in order not to lose reactivity.

  3. It is not recommended destructure: it is possible to lose responsiveness this way.


Conclusion

Vue provides two API to make state reactive: ref() and reactive() , with the first choice recommended way, accomplice the fact some limitations of second choice.


Happy coding!✨