EmilianoDecember 26, 2024

How Reactivity Works in Vue 3

What is reactivity?

In the context of Vue, reactivity is the ability to track changes in data and efficiently update the user interface (UI).

When you declare reactive data, Vue turns it into reactive state and associates it with dependencies that need to be notified when that data changes.

import { reactive } from "vue";

const state = reactive({
    counter: 0,
});

state.counter++;

Vue 3 uses Proxies to implement reactivity. A Proxy is a JavaScript feature that allows intercepting and redefining operations such as reading, writing, or deleting properties on an object.

Simple Proxy example

const handler = {
    get(target, key) {
        console.log(`Accessing property ${key}`);
        return target[key];
    },
    set(target, key, value) {
        console.log(`Modifying property ${key} to ${value}`);
        target[key] = value;
        return true;
    }
};

const reactiveObject = new Proxy({ name: "Vue", version: 3 }, handler);

console.log(reactiveObject.name);
reactiveObject.version = 4;

In Vue 3, this same principle is applied to transform objects declared with reactive or ref into reactive structures.

Types of reactivity in Vue 3

Reactivity with reactive

The reactive method converts an object into a reactive proxy. Every time you access or modify its properties, Vue records dependencies and notifies affected components.

const state = reactive({
    counter: 0,
});

state.counter++;

Reference-based reactivity with ref

ref is used to create simple reactive values, such as primitives or data structures that do not need to be complex objects.

import { ref } from "vue";

const count = ref(0);

count.value++;

Vue uses an internal system that tracks dependencies when reactive properties are accessed. This happens in the context of a reactive function such as computed or watchEffect.

<script setup>
import { reactive, watchEffect } from "vue";

const state = reactive({
    message: "Hello, Vue!",
});

watchEffect(() => {
    console.log(state.message); // This will run whenever state.message changes
});

state.message = "Reactivity in action!";
</script>

Reactivity lifecycle

  • Creation: Initial data is wrapped in proxies through reactive or ref.
  • Tracking: When data is accessed inside a reactive context, Vue records the relationship between the data and the associated effect, such as updating the UI.
  • Notification: When data changes, Vue automatically notifies all associated effects so they can update.

For more information, you can check Vue's official documentation on Reactivity in Depth.