Proxy-Based Reactivity: Implementing reactive
🎯 Introduction
In the Vue 3 course, we use reactive to create reactive objects: change a property, and the template updates automatically. How does that happen? How does Vue know which part of the UI needs updating?
The answer is the ES6 Proxy. In this article, we explore packages/reactivity to see what reactive does internally. By the end, you will be able to:
- Explain how the
getandsettraps intercept property reads and writes. - Understand the WeakMap cache and recursive wrapping in
reactive. - Identify the limitations of Vue 2 reactivity that Vue 3 addresses.
- Recognize the limitations of
reactiveand whyrefis still necessary.
The source excerpts use Vue 3.5.x from the GitHub vuejs/core monorepo, primarily packages/reactivity/src/reactive.ts and packages/reactivity/src/baseHandlers.ts. Run the examples directly with Node.js v22.
🧱 A Quick Review of Proxy
Before reading reactive, we need to understand its foundation: what is a Proxy, and what can it do? A Proxy wraps an object in an intermediary layer. Reads and writes through that wrapper pass through this layer first, where we can add logic, such as logging, before forwarding the operation to the original object.
This is called intercepting an operation. The object that defines these interception methods, or traps, is the handler. The basic syntax is new Proxy(target, handler):
const user = { name: 'noxussj' }; // target: the original object being wrapped
const proxyUser = new Proxy(user, {
// Property reads pass through this trap first
get(target, key) {
console.log('Read', key);
return target[key]; // Forward the read to the original object
},
// Property writes pass through this trap first
set(target, key, value) {
console.log('Set', key, 'to', value);
target[key] = value; // Forward the write to the original object
return true; // Report that the assignment succeeded
},
});
proxyUser.name; // Logs: Read name
proxyUser.name = 'Ming'; // Logs: Set name to Ming
Run node demo.js with Node.js v22 to see both operations intercepted. We have not modified the structure of user; we have wrapped it instead.
true from the set trap to indicate success. Otherwise, assignment throws in strict mode. The proxy and original object also share the same underlying data: changing proxyUser.name changes user.name too.This follows the same principle as the Object.defineProperty getters and setters in the Vue 2 source code course: both intercept reads and writes. The difference is that defineProperty handles one existing property at a time, while Proxy intercepts operations on the entire object. That distinction underlies the changes we will see next.
🧱 Implementing reactive
Now that we know how Proxy works, let's see how Vue 3 uses it. The implementation has two main parts: the entry function in reactive.ts and the handlers in baseHandlers.ts.
First, the entry function creates the proxy. Internally, reactive calls createReactiveObject: wrap eligible values and reuse existing proxies.
// Simplified from packages/reactivity/src/reactive.ts
const reactiveMap = new WeakMap(); // Cache: original object → proxy
function reactive(target) {
return createReactiveObject(target, reactiveMap);
}
function createReactiveObject(target, proxyMap) {
// First check: return non-objects unchanged
if (typeof target !== 'object' || target === null) {
return target;
}
// Second check: reuse a cached proxy
const existingProxy = proxyMap.get(target);
if (existingProxy) {
return existingProxy;
}
// Otherwise, create a proxy and cache it
const proxy = new Proxy(target, mutableHandlers);
proxyMap.set(target, proxy);
return proxy;
}
The WeakMap named reactiveMap acts as a cache. Each time a proxy is created, it records the mapping from the original object to that proxy. Passing in the same object again returns the cached proxy. For this example, think of it as a Map indexed by objects. Its relevant differences from a regular Map are that these keys are objects and that they do not prevent garbage collection.
Second, mutableHandlers contains the interception logic at the heart of reactivity. These are the handlers passed to the Proxy above. The read and write operations work as follows:
// Simplified from packages/reactivity/src/baseHandlers.ts
const mutableHandlers = {
get(target, key, receiver) {
// 1. Read the value normally (Reflect plays the role of target[key])
const res = Reflect.get(target, key, receiver);
// 2. Track dependencies: record which effect uses this property
// Covered in the next article; placeholder: track(target, key)
// 3. If the value is an object, make it reactive too
if (typeof res === 'object' && res !== null) {
return reactive(res);
}
return res;
},
set(target, key, value, receiver) {
// 1. Update the value normally
const result = Reflect.set(target, key, value, receiver);
// 2. Trigger updates for consumers of this property; covered next
// trigger(target, key)
return result;
},
};
Three concepts here deserve a closer look:
- Reflect provides methods corresponding to object operations.
Reflect.get(target, key)behaves liketarget[key]in simple cases. Vue uses Reflect to preserve the correct behavior in cases involving inheritance. For now, read these calls as ordinary reads and writes. track()(dependency tracking) records which effect uses a value when it is read. A dependency connects that value to a consumer, such as a render function. This is only a placeholder comment here; we will implement it when coveringeffectnext.trigger()(triggering updates) notifies those consumers when the value changes. We will explore this in the next article too.
The overall pattern is: track dependencies on reads and trigger updates on writes, using Proxy to intercept both.
🧱 Lazy Wrapping and Caching
Two design choices in the simplified code are easy to overlook: when are nested objects wrapped, and can the same object be wrapped repeatedly? Both choices help performance.
First, lazy wrapping: nested objects are passed to reactive only when accessed through get.
Recall step 3 of the get trap: only when the retrieved value is an object do we call reactive(res). Vue 3 does not eagerly wrap the entire object tree during initialization. It wraps each level as you access it:
const state = reactive({
user: { info: { city: 'Hangzhou' } },
});
// Reading only state.user leaves info unwrapped
// info becomes a proxy when state.user.info is read
Think of furnishing a house: instead of furnishing every room on the day you buy it, you furnish each room when you need it. For deeply nested objects where only some properties are used, this avoids considerable initialization work.
reactive(res) checks the WeakMap internally, so the same nested object is wrapped only once, regardless of how often it is accessed.Second, caching: reuse proxies that already exist.
The WeakMap in createReactiveObject ensures that a given original object has one cached reactive proxy. In practice:
const raw = { name: 'noxussj' };
reactive(raw) === reactive(raw); // true: both calls return the same proxy
⚡ Which Vue 2 Limitations Does This Address?
How does this Proxy approach improve on Vue 2? Recall two familiar limitations from the Vue 2 source code course: adding object properties does not trigger updates, and assigning array elements by index or changing length does not trigger updates. These required workarounds such as this.$set or splice.
The root cause is that defineProperty intercepts only properties configured during initialization. Newly added properties have no interception logic. Proxy instead intercepts operations on the entire object: reads and writes for any key pass through its traps, addressing these limitations in Vue 3:
<script setup>
import { reactive } from 'vue';
const user = reactive({ name: 'noxussj' });
const list = reactive(['a', 'b', 'c']);
function test() {
user.age = 18; // Does not trigger updates in Vue 2; works in Vue 3
list[0] = 'z'; // Does not trigger updates in Vue 2; works in Vue 3
list.length = 1; // Does not trigger updates in Vue 2; works in Vue 3
}
</script>
Adding age invokes the set trap as usual. To Proxy, list[0] and list.length are property operations too, so they are intercepted in the same way. The special $set workaround is no longer needed in Vue 3.
Vue 3 also no longer needs Vue 2's mechanism of overriding seven array methods to detect these mutations: Proxy can observe index writes and length changes caused by push through the same interception mechanism. This makes the underlying model easier to understand.
🪤 Limitations of reactive
Proxy is powerful, but reactive still has boundaries. Two are particularly useful to understand in everyday development.
First, only objects can be wrapped.
The initial check in createReactiveObject returns non-objects unchanged. Primitive values, such as strings and numbers, therefore cannot be made reactive with reactive:
const count = reactive(0); // Ineffective: 0 is not an object and is returned unchanged
Second, destructuring can disconnect values from reactivity.
Reactivity depends on operations passing through the Proxy. Destructuring reads a property and assigns its value to a separate variable. For a primitive property, that variable no longer interacts with the proxy:
const state = reactive({ count: 0 });
const { count } = state; // count is just the ordinary number 0
count++; // Attempts to change the separate variable; the view will not update
These limitations explain why ref exists. How can a primitive be reactive, or a destructured property retain its reactive connection? Wrap the value in an object with a .value property. We will explore the implementation in the article on ref and computed.
toRefs. See the Vue 3 course for usage details.❓ Questions and Answers
Q1: Why can Proxy intercept new properties when defineProperty cannot?
During initialization, defineProperty installs getters and setters on each existing property. Properties added later have no interception logic. Proxy intercepts operations on the whole object instead: its set trap receives assignments whether the key already exists or is new.
Q2: Why wrap nested objects on access instead of wrapping everything at once?
Primarily for performance. A large object may be deeply nested while only a small portion is used. Eagerly wrapping everything does unnecessary work. Lazy wrapping defers that cost until access, and the WeakMap cache ensures each nested object is wrapped only once.
Q3: Why use Reflect.get and Reflect.set instead of targetkey?
They behave similarly in simple cases, but Reflect methods accept a receiver. This ensures that this inside an accessor such as a getter refers to the proxy rather than the original object, preserving behavior in cases involving prototype inheritance. You do not need to master this detail yet; reading Reflect calls as ordinary reads and writes is enough to follow the main flow.
Q4: What about browser support for Proxy?
Proxy cannot be fully polyfilled, so Vue 3 does not support older browsers such as IE. This is one reason Vue 3 dropped IE support. Modern browsers such as Chrome, Firefox, Safari, and Edge support Proxy.
Q5: Does calling reactive repeatedly on the same object create multiple proxies?
No. createReactiveObject checks its WeakMap cache first. It creates one proxy for an original object and reuses it afterward, so reactive(raw) === reactive(raw) is true.
🧪 Exercise
Without looking up the implementation, complete this mini reactive. Use Proxy to log Read xxx on reads and Set xxx to newValue on writes. Include a WeakMap cache so repeated calls with the same object reuse its proxy. Save it as a .js file and run it with Node.js v22.
const proxyMap = new WeakMap();
function reactive(target) {
// Your code here (hint: return non-objects; check the cache; create a Proxy)
}
const user = { name: 'noxussj' };
const proxyUser = reactive(user);
// Expected output:
// Read name
// Set name to Ming
console.log(proxyUser.name);
proxyUser.name = 'Ming';
// Check the cache: both calls should return the same object
console.log(reactive(user) === proxyUser); // true
For an extra challenge, add a nested object to user, such as info: { city: 'Hangzhou' }. Will your implementation log changes to proxyUser.info.city? Which part needs to change to support lazy wrapping?
🎉 You now understand the core of Vue 3's Proxy-based reactivity! Next, we will explore effect and dependency tracking: where track() records consumers and how trigger() notifies precisely the effects that need to update.
