JAVASCRIPT

Understanding Vue 3 Reactivity: When to Use ref vs. reactive

Explore the differences and best use cases for `ref` and `reactive` in Vue 3 Composition API to effectively manage component state and ensure optimal reactivity and performance.

// src/components/ReactivityExample.vue
<template>
  <h2>Ref Example</h2>
  <p>Count: {{ count }}</p>
  <button @click="incrementCount">Increment Ref</button>

  <h2>Reactive Example</h2>
  <p>Name: {{ user.name }}</p>
  <p>Age: {{ user.age }}</p>
  <button @click="incrementAge">Increment Reactive Age</button>
  <button @click="changeName">Change Reactive Name</button>

  <h2>Array in Reactive</h2>
  <ul>
    <li v-for="item in items.list" :key="item.id">{{ item.text }}</li>
  </ul>
  <button @click="addItem">Add Item</button>

  <h2>Ref for Objects/Arrays</h2>
  <p>Object Ref Name: {{ person.name }}</p>
  <button @click="changePersonName">Change Person Name (Ref)</button>
</template>

<script setup>
import { ref, reactive } from 'vue';

// 1. Using `ref` for primitive values (numbers, strings, booleans)
const count = ref(0);
const incrementCount = () => {
  count.value++; // Access with .value
};

// 2. Using `reactive` for objects and arrays
const user = reactive({
  name: 'Alice',
  age: 30,
  skills: ['Vue', 'JS']
});

const incrementAge = () => {
  user.age++; // Directly mutate properties of the reactive object
};

const changeName = () => {
  user.name = 'Bob'; // Directly mutate properties
};

// `reactive` for an object containing an array
const items = reactive({
  list: [
    { id: 1, text: 'Item 1' },
    { id: 2, text: 'Item 2' }
  ]
});

const addItem = () => {
  items.list.push({ id: items.list.length + 1, text: `Item ${items.list.length + 1}` });
};

// 3. Using `ref` for objects and arrays (Vue automatically unwraps it in templates)
const person = ref({
  name: 'Charlie',
  job: 'Engineer'
});

const changePersonName = () => {
  person.value.name = 'David'; // Access the object via .value, then its properties
};
</script>
How it works: This snippet illustrates the fundamental differences and appropriate use cases for `ref` and `reactive` in Vue 3's Composition API. `ref` is primarily used to make primitive values (like numbers, strings, booleans) reactive, requiring `.value` to access or mutate them in script, but automatically unwrapped in templates. `reactive` is used for creating reactive objects or arrays, allowing direct property access and mutation. While `ref` can also hold objects/arrays, `reactive` is often preferred for complex state objects as it removes the need for `.value` for inner properties, leading to cleaner code for deeply nested reactive data.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs