JAVASCRIPT

Understanding Vue 3 Reactivity: `ref` vs `reactive`

Master Vue 3 reactivity by learning the core differences and appropriate use cases for `ref` and `reactive` to manage component state efficiently.

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

// Using ref for primitive values and single reactive objects
const count = ref(0);
const message = ref('Hello Vue 3');

const userRef = ref({
  name: 'Alice',
  age: 30
});

// Using reactive for complex objects (proxies the object directly)
const state = reactive({
  items: [],
  isLoading: false
});

onMounted(() => {
  console.log('Count:', count.value); // Access ref value with .value
  console.log('Message:', message.value);

  count.value++; // Mutate ref value with .value

  userRef.value.age = 31; // Mutate object inside ref via .value

  state.isLoading = true; // Mutate reactive properties directly
  setTimeout(() => {
    state.items.push('Item 1', 'Item 2');
    state.isLoading = false;
    console.log('Reactive state items:', state.items);
  }, 1000);
});
</script>

<template>
  <div>
    <p>Count: {{ count }}</p>
    <p>Message: {{ message }}</p>
    <p>User Ref: {{ userRef.name }} ({{ userRef.age }})</p>
    <p v-if="state.isLoading">Loading items...</p>
    <ul v-else>
      <li v-for="item in state.items" :key="item">{{ item }}</li>
    </ul>
  </div>
</template>
How it works: In Vue 3's Composition API, `ref` is used to make any value reactive, including primitives (numbers, strings, booleans) and objects. For primitives, `ref` creates a reactive object with a `.value` property that holds the actual value. For objects, `ref` makes the object itself reactive via `.value`. `reactive` is specifically used to make an object reactive, creating a proxy around it. You access and mutate properties of `reactive` objects directly, while `ref` values always require `.value` to access or modify. Choose `ref` for primitives and when swapping the entire object, and `reactive` for complex object states where you're primarily modifying properties within the same object.

Need help integrating this into your project?

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

Hire DigitalCodeLabs