What is the Vue reactivity system and how does it work?

What is the Vue reactivity system and how does it work?

What is the Vue reactivity system and how does it work?

Question

How does Vue 3's reactivity system work under the hood?

Answer

Vue 3 implements reactivity using JavaScript Proxies (ES6+). When you call reactive() or ref(), Vue wraps the value in a Proxy that intercepts all property access and mutations.

How it Tracks Dependencies

  1. Track (get) — when a reactive property is read inside a computed or watchEffect, Vue records which "effect" depends on it
  2. Trigger (set) — when that property is written to, Vue looks up all effects that depend on it and re-runs them
import { reactive, watchEffect } from 'vue'

const state = reactive({ count: 0 })

watchEffect(() => {
  // Vue tracks that this effect reads state.count
  console.log(state.count)
})

state.count++ // Vue triggers the effect → logs new value

ref vs reactive internals

// ref() wraps the value in an object with a .value getter/setter
const count = ref(0)
// Internally: { get value() { track(); return _value }, set value(v) { _value = v; trigger() } }

// reactive() wraps the object in a Proxy
const obj = reactive({ name: 'Alice' })
// Internally: new Proxy(obj, { get: track, set: trigger })

Why Proxies over Object.defineProperty (Vue 2)?

  • Vue 2 could not detect property addition/deletion — Vue 3 Proxies can
  • Vue 2 could not detect array index mutations — Proxies handle them natively
  • Proxies intercept the full object, not individual properties
All Comments