Blog>
Snippets

Reactivity with refs vs. reactive

Compare the usage of ref and reactive to make variables reactive in Composition API and discuss the subtle differences.
import { ref, reactive } from 'vue';

// Using ref for a primitive value
const countWithRef = ref(0);

function incrementRef() {
  countWithRef.value++;
}
This snippet shows how to make a primitive value reactive using the ref function from Vue's Composition API. The ref function takes a primitive value and returns a reactive and mutable ref object. To access or modify the value, we use '.value'. The incrementRef function demonstrates how to update the reactive value.
import { ref, reactive } from 'vue';

// Using reactive for an object
const stateWithReactive = reactive({ count: 0 });

function incrementReactive() {
  stateWithReactive.count++;
}
In this snippet, we use the reactive function to create a reactive state with an object. The reactive function takes an object and returns a reactive proxy of the original object. Any property of the reactive object is automatically tracked, and when mutated, it updates the component. The incrementReactive function shows how the count property in the reactive object can be directly mutated without '.value'.
import { ref, reactive } from 'vue';

// Comparing ref with an object to reactive
const objectWithRef = ref({ count: 0 });
const objectWithReactive = reactive({ count: 0 });

function compareReactivity() {
  objectWithRef.value.count++;
  objectWithReactive.count++;

  // When logging, a ref with an object requires .value to access the object
  console.log(objectWithRef.value); // { count: 1 }
  // A reactive object can be accessed directly
  console.log(objectWithReactive); // { count: 1 }
}
This comparison shows that a ref can also hold an object and make it reactive. However, accessing or mutating any property of the object inside the ref requires the use of '.value'. Using reactive is more straightforward for objects as you can directly mutate and access the properties of the object without '.value'. The compareReactivity function demonstrates how the count property is incremented in both scenarios.