ref vs reactive in Vue 3?

In Vue.js, “ref” and “reactive” are two different mechanisms for working with data and reactivity, and they serve slightly different purposes.


Basic Usage:

ref is primarily used to create a reactive reference to a mutable value, such as a primitive (like a number or a string) or an object. It is often used when you need to directly modify the value.


The value stored in a ref can be directly mutated without losing reactivity. When the value inside a ref changes, any components or parts of your application that depend on it will automatically re-render.


import { ref } from 'vue';

const count = ref(0);

// Later in a component
count.value++; // Changes are reactive


Basic Usage:

reactive is used to create a reactive object or to make an existing object reactive. It’s commonly used for more complex data structures like objects and arrays.


When you wrap an object with reactive, you create a Proxies-based reactivity system, which means any property access or mutation is tracked and can trigger reactivity.


import { reactive } from 'vue';

const state = reactive({
  count: 0,
  message: 'Hello, Vue!',

// Later in a component
state.count++; // Changes are reactive

In summary

Use ref for individual values that you want to directly mutate and make reactive. It’s especially useful for primitive types.

Use reactive for more complex data structures like objects and arrays. It provides a more granular level of reactivity, tracking changes to individual properties within the object.

Subscribe for
weekly updates