Sobes.tech
Middle+

Tell me about ref and reactive in Vue 3: differences, when to use.

sobes.tech AI

Answer from AI

In Vue 3, ref and reactive are two ways to create reactive data, but with different use cases:

  • ref creates a reactive object that contains a single value in the .value property. It is used for primitive types (numbers, strings, booleans) or when you need to reactively track a single value.

  • reactive creates a reactive proxy for an object or array, allowing you to track changes to all nested properties.

Differences:

  • ref wraps a primitive or object in a container with .value.
  • reactive works only with objects and returns a proxy without an additional property.

When to use:

  • If you need to store a primitive reactively — use ref.
  • If you are working with an object or array and want to track all changes reactively — use reactive.

Example:

import { ref, reactive } from 'vue';

const count = ref(0); // reactive number
const state = reactive({ name: 'Vue', version: 3 }); // reactive object

count.value++;
state.version = 4;

In Vue templates, ref is automatically unwrapped, so you can just write {{ count }}.