Reactivity Internals and Advanced APIs

Understand Vue 3 reactivity, the differences between ref and reactive, and advanced APIs such as toRefs, toRaw, and readonly.

🎯 Introduction

By the end of this article, you will understand how Vue 3's reactivity system works, how ref and reactive differ internally, and when to use advanced APIs such as toRefs, toRef, toRaw, markRaw, and readonly. You will also learn to avoid common pitfalls, including losing reactivity through destructuring or replacing reactive objects, so that your Vue 3 code behaves reliably.


🧱 Why Vue 3 Replaces Object.defineProperty with Proxy

Vue 2's reactivity system uses Object.defineProperty. It traverses an object's properties and intercepts access through getters and setters, allowing Vue to notify the view when data changes.

However, this approach has several limitations:

  • It cannot detect newly added or deleted object properties automatically.
  • It cannot directly detect array index assignments or length changes.
  • It must recursively traverse the entire object, adding initialization overhead.

Vue 3 uses ES6 Proxy to intercept operations on an entire object, without traversing every property in advance.

const user = { name: 'Zhang San', age: 20 };
const proxyUser = new Proxy(user, {
    get(target, key) {
        console.log('Read', key);
        return target[key];
    },
    set(target, key, value) {
        console.log('Updated', key, 'to', value);
        target[key] = value;
        return true;
    },
});

proxyUser.name = 'Li Si'; // Updated name to Li Si
console.log(proxyUser.age); // Read age
Proxy can intercept reads, writes, additions, and deletions of object properties, making Vue 3's reactivity more capable and flexible.

Vue 3 builds on Proxy internally. Calling reactive() on an object returns a reactive proxy of this kind.


⚡ How ref and reactive Differ Internally

Both ref and reactive create reactive data, but their use cases and implementations differ.

reactive Accepts Only Objects

import { reactive } from 'vue';

const state = reactive({ count: 0 });
state.count++; // Triggers reactive updates

Passing a primitive to reactive produces an error or fails to make it reactive:

const num = reactive(0); // Not reactive

ref Can Wrap Any Value

import { ref } from 'vue';

const count = ref(0); // Primitive value
const user = ref({ name: 'Zhang San' }); // Object value

ref returns an object that stores its underlying value in the .value property:

console.log(count.value); // 0
count.value++;

Why Does ref Wrap Values in an Object?

JavaScript primitives such as numbers, strings, and booleans are passed by value. Returning a number directly gives the caller a copy whose changes cannot be tracked. ref wraps the value in an object and uses a getter and setter on .value to provide reactivity.

One further detail: when ref wraps an object, Vue also converts that object into a reactive object internally. Thus, ref({ name: 'Zhang San' }) and reactive({ name: 'Zhang San' }) provide the same deep reactivity; ref adds the .value wrapper.
As a simple guideline, use ref for primitives and consider reactive for objects. In practice, ref is also very common in script setup, especially when values need to be destructured or returned from functions.

🪤 Common Ways to Lose Reactivity

Vue 3's reactivity system is powerful, but some patterns can silently break reactive connections. Here are common pitfalls.

Pitfall 1: Destructuring a reactive Object

import { reactive } from 'vue';

const user = reactive({ name: 'Zhang San', age: 20 });
let { name } = user;

name = 'Li Si'; // The view does not update: name is now a plain string

Here, name is a plain string disconnected from the reactive object.

Correct approach: use toRefs

import { reactive, toRefs } from 'vue';

const user = reactive({ name: 'Zhang San', age: 20 });
const { name, age } = toRefs(user);

name.value = 'Li Si'; // The view updates

toRefs converts each object property into a ref, preserving its reactive connection after destructuring.


Pitfall 2: Replacing an Entire reactive Object

import { reactive } from 'vue';

let user = reactive({ name: 'Zhang San' });

user = { name: 'Li Si' }; // Reactivity is lost

reactive() returns a proxy. Reassigning the variable directly disconnects it from that proxy.

Correct approach: update properties instead of replacing the object

user.name = 'Li Si';

If you need to replace the entire value, use ref:

import { ref } from 'vue';

const user = ref({ name: 'Zhang San' });
user.value = { name: 'Li Si' }; // Remains reactive

Pitfall 3: Copying Reactive Data into a Plain Variable and Modifying It

const state = reactive({ count: 0 });
let count = state.count;
count++;

Here, count has been disconnected from the reactive object and is now a plain number.

Correct approach: update through the reactive object or a ref's .value


🧰 Common Advanced APIs

The following APIs are particularly useful in more complex scenarios.

toRefs: Preserve Reactivity When Destructuring

Use toRefs when exposing a reactive object's properties to a template or returning them from a composable.

UserInfo.vue
<template>
    <div>
        <p>Name: {{ name }}</p>
        <p>Age: {{ age }}</p>
        <button @click="age++">Add one year</button>
    </div>
</template>

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

const user = reactive({ name: 'Zhang San', age: 20 });
const { name, age } = toRefs(user);
</script>
Each property in the object returned by toRefs is a ref. Templates can use {{ name }} directly, but JavaScript code must update it through name.value.

toRef: Create a Ref for One Property

To turn a single property of a reactive object into a ref, use toRef:

import { reactive, toRef } from 'vue';

const user = reactive({ name: 'Zhang San', age: 20 });
const name = toRef(user, 'name');

name.value = 'Li Si'; // user.name updates as well

How Do toRef and toRefs Differ?

  • toRefs converts all enumerable properties of a reactive object into refs, making it useful for destructuring several properties at once.
  • toRef converts one specified property, making it useful when you only need an individual property.
import { reactive, toRefs, toRef } from 'vue';

const user = reactive({ name: 'Zhang San', age: 20 });

// Convert multiple properties to refs
const { name, age } = toRefs(user);

// Convert a single property
const nameOnly = toRef(user, 'name');

toRaw: Access the Original Object

Sometimes you need the original object behind a reactive proxy, for example when passing it to a third-party library that does not work with reactive proxies:

import { reactive, toRaw } from 'vue';

const state = reactive({ name: 'Zhang San' });
const rawState = toRaw(state);

console.log(rawState); // { name: 'Zhang San' }, a plain object
Changing the raw object returned by toRaw does not trigger view updates. Typically, use it only to read data or pass it to external code.

markRaw: Opt an Object Out of Reactivity

Some data does not need to be reactive, such as a large static configuration object or a third-party class instance. Use markRaw to skip reactive conversion and reduce overhead.

import { markRaw } from 'vue';

const bigConfig = markRaw({
    list: [/* Large dataset */],
    settings: { theme: 'dark' },
});
markRaw is useful for complex objects, class instances, and chart instances that do not need reactive tracking.

Why Not Just Use a Plain Object?

A plain object is fine when used independently in a component. The key purpose of markRaw is that Vue will not convert the object into a reactive proxy even when it is placed inside reactive or ref.

Compare these examples:

import { reactive, markRaw } from 'vue';

// Plain object: Vue converts it into a reactive proxy
const normalConfig = { theme: 'dark' };
const state1 = reactive({ config: normalConfig });
state1.config.theme = 'light'; // Triggers dependent updates

// Object marked with markRaw: not converted into a proxy
const rawConfig = markRaw({ theme: 'dark' });
const state2 = reactive({ config: rawConfig });
state2.config.theme = 'light'; // Does not trigger dependent updates, reducing overhead

Use markRaw when an object needs to live inside reactive state without incurring reactive tracking overhead.


readonly: Create a Read-Only View of Reactive Data

Use readonly when data should remain reactive but should be protected against accidental changes:

import { reactive, readonly } from 'vue';

const state = reactive({ count: 0 });
const readOnlyState = readonly(state);

readOnlyState.count++; // Warns in the console; the mutation has no effect
readonly is often used to expose internal state to other components for reading while preventing direct external mutations.

How Does This Differ from Returning a computed Value?

computed derives a new value from existing data. A getter-only computed ref is read-only, but it does not prevent changes to the original data.

import { reactive, computed } from 'vue';

const state = reactive({ count: 0 });
const readOnlyCount = computed(() => state.count);

readOnlyCount.value++; // Rejected: the computed ref is read-only
state.count++; // The original data can still be changed

By contrast, readonly proxies the original data directly. External code cannot mutate it through this proxy, while internal changes to the source are reflected in the read-only view.

import { reactive, readonly } from 'vue';

const state = reactive({ count: 0 });
const readOnlyState = readonly(state);

state.count++; // Change the original data internally
console.log(readOnlyState.count); // 1: the read-only view updates as well

readOnlyState.count++; // External mutation warns and has no effect
readonly is deep: nested properties are also protected against external mutation through the read-only proxy.

A simple way to distinguish them:

  • computed derives B from A.
  • readonly exposes A while preventing mutations through the exposed view.

isRef / isReactive / isProxy: Checking Values

Reusable logic and composables often need to check whether a value is reactive:

import { ref, reactive, isRef, isReactive, isProxy } from 'vue';

const count = ref(0);
const user = reactive({ name: 'Zhang San' });

console.log(isRef(count)); // true
console.log(isReactive(user)); // true
console.log(isProxy(user)); // true
isProxy checks for proxies created by APIs such as reactive and readonly, so its scope is broader than isReactive.

unref: Unwrap a Ref

If a value might be either a plain value or a ref, use unref to retrieve the underlying value:

import { ref, unref } from 'vue';

const count = ref(10);
const num = 20;

console.log(unref(count)); // 10
console.log(unref(num)); // 20
unref is useful in general-purpose functions that accept either refs or plain values.

🛠 Putting It Together: A Form Example

The following user form combines reactivity APIs such as reactive and readonly, alongside validation and access to the raw data:

UserForm.vue
<template>
    <form @submit.prevent="submit">
        <input v-model="form.name" placeholder="Name" />
        <input v-model="form.email" placeholder="Email" />
        <button type="submit" :disabled="!isValid">Submit</button>
    </form>
</template>

<script setup>
import { reactive, computed, toRaw, readonly } from 'vue';

// 1. Define the form object with reactive
const form = reactive({
    name: '',
    email: '',
});

// 2. Use computed to check whether the form is valid
const isValid = computed(() => {
    return form.name.trim() !== '' && form.email.includes('@');
});

// 3. Get the raw data on submission to send to an API
function submit() {
    const payload = toRaw(form);
    console.log('Submitted data', payload);
}

// 4. Expose a read-only view of the form to a parent component if needed
const readOnlyForm = readonly(form);
</script>
In practice, reactive works well for structured data such as forms. Combined with computed for validation, it keeps logic clear and easy to maintain.

❓ Questions and Answers

Q1: Why does Vue 3 replace Object.defineProperty with Proxy?

Proxy can detect property additions, deletions, and array changes without recursively traversing the entire object at initialization, improving performance and flexibility.

Q2: What is the fundamental difference between ref and reactive?

ref wraps any value in an object accessed through .value. reactive creates a Proxy around an object, whose properties are accessed directly.

Q3: Why can destructuring a reactive object lose reactivity?

Destructured primitive properties become plain values disconnected from the proxy. Use toRefs to preserve their reactive connections.

Q4: How does readonly differ from ordinary reactive data?

A readonly view of reactive data still reflects updates but prevents mutations through that view, making it useful for exposing internal state.


🧪 Exercises

Exercise 1

Complete the following code using toRefs to keep the destructured property reactive:

<template>
    <div>
        <p>City: {{ city }}</p>
        <button @click="city = 'Shanghai'">Switch city</button>
    </div>
</template>

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

const location = reactive({ city: 'Beijing', code: 100000 });

// Use toRefs here to destructure city while preserving reactivity
</script>

Exercise 2

Implement a useReadOnlyUser composable that accepts a user object and returns read-only reactive user data together with update methods. Only the internal methods should mutate the state.

import { reactive, readonly } from 'vue';

export function useReadOnlyUser(initialUser) {
    // Implement here
}

🎉 You now understand Vue 3 reactivity internals and common advanced APIs! This knowledge will help you avoid reactivity pitfalls and write more robust Vue 3 code.