Sobes.tech
Middle

What is the difference between ref and reactive in Vue 3?

sobes.tech AI

Answer from AI

In Vue 3, ref and reactive are two ways to create reactive data, but they differ in purpose and the types of data they work with.

  • ref is used to create a reactive object that contains a primitive value or an object in its .value property. It is a wrapper around the value that allows tracking its changes.

  • reactive creates a reactive proxy object from the passed object, allowing direct tracking of changes to its properties.

Example:

import { ref, reactive } from 'vue';

const count = ref(0); // reactive primitive value
count.value++;

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

Key differences:

  • ref is suitable for primitives (numbers, strings, booleans) and when you need to reactively track a single value.
  • reactive is better for objects and arrays to make all their properties reactive.

In Vue templates, ref is automatically unwrapped, so you can just write {{ count }}, but in code, you need to access .value.

Summary:

  • Use ref for simple values or when you need reactivity of a single value.
  • Use reactive for complex objects with multiple properties.
What is the difference between ref and reactive in… - sobes.tech