Sobes.tech
Senior

What is the difference between ref and reactive in Vue.js?

sobes.tech AI

Answer from AI

In Vue.js, ref and reactive are two ways to create reactive data, but they have different purposes and features.

  • ref creates a reactive object with a single property .value. It is used for primitive values (numbers, strings, booleans) or when you need to wrap a single value in reactivity.

    import { ref } from 'vue';
    const count = ref(0);
    count.value++;
    
  • reactive creates a reactive object from an object or array. It returns a proxy object that tracks changes to all nested properties.

    import { reactive } from 'vue';
    const state = reactive({ count: 0 });
    state.count++;
    

Main differences:

  • ref is used for primitives or when you need to reactively track a single value.
  • reactive is used for reactivity of complex objects and data structures.
  • When using ref for objects, access to the value is through .value, while with reactive — directly.

In Vue 3, both approaches are often combined depending on the situation to manage reactivity effectively.