How ref and computed Work: Wrappers and Lazy Evaluation
🎯 Introduction
The previous articles covered reactive and effect: Proxy intercepts object operations, while effects track consumers and respond to changes. But Proxy can only wrap objects—what about primitives such as strings and numbers? You cannot create a proxy around the number 18. Vue 3's answer is ref. In this article, we explore ref and computed so you can:
- Explain why primitives need
refand what.valueintercepts. - Read the
RefImplimplementation: tracking consumers on reads and notifying them on writes. - Understand computed's lazy evaluation and caching through a dirty flag.
- Explain ref unwrapping in templates and why destructuring a ref's value can lose its reactive connection.
The excerpts use Vue 3.5.x from the GitHub vuejs/core repository, primarily packages/reactivity/src/ref.ts and packages/reactivity/src/computed.ts. The examples can be run with Node.js v22.
🧱 Why ref Is Necessary
How can Vue detect a change to an ordinary number?
As article 3 explained, reactive uses Proxy, and Proxy intercepts operations on objects. Interception means inserting Vue's logic into a read or write so it can observe the operation. Compare:
// Object: operations can be intercepted by Proxy
const state = reactive({ count: 0 });
state.count++; // Property reads and writes pass through Proxy
// Primitive: no interceptable property operation
let count = 0;
count++; // An ordinary variable assignment that Vue cannot observe
A primitive is stored directly in a variable. JavaScript provides no hook for intercepting arbitrary reads or assignments to that local variable, so Proxy cannot detect count++. Vue's solution is to wrap the value in an object and intercept access to a property instead. That property is .value:
// A ref is an object with a .value property
const count = ref(0);
count.value++; // Both reading and writing .value can be intercepted
Now both operations are object property accesses. Article 3 intercepted properties with Proxy; here we will use class getters and setters. This wrapper allows the same reactive mechanism to work for primitives.
🧱 Implementing RefImpl
How does Vue implement this wrapper? ref() creates an instance of a class called RefImpl. We will examine a teaching version with TypeScript annotations and peripheral branches omitted. First, the constructor stores the value:
// Simplified from packages/reactivity/src/ref.ts
class RefImpl {
constructor(value) {
// Convert objects to reactive objects
this._value = isObject(value) ? reactive(value) : value;
// Preserve the raw value for later comparisons
this._rawValue = value;
}
}
Next, intercept reads and writes with accessors. Reading .value invokes get value(); assigning it invokes set value(). Vue places its tracking logic in these accessors:
get value() {
// Track the currently executing effect as a consumer of this ref
trackRefValue(this);
return this._value;
}
set value(newVal) {
// hasChanged compares values using Object.is; unchanged values need no update
if (hasChanged(newVal, this._rawValue)) {
this._rawValue = newVal;
// Convert a new object value to a reactive object too
this._value = isObject(newVal) ? reactive(newVal) : newVal;
// Notify registered effects to rerun
triggerRefValue(this);
}
}
trackRefValue represents the dependency tracking from article 4: register effects that use the value so Vue knows whom to notify later. triggerRefValue performs the notification. ref() itself simply returns a new RefImpl instance. Two details matter:
- Assigning the same value does not trigger updates.
hasChangedavoids unnecessary work. - Object values are converted with
reactive. Afterref({ name: 'noxussj' }), changinguserRef.value.namecan trigger updates through that object's Proxy.
🧱 Automatic Ref Unwrapping in reactive Objects
When a ref is a property of a reactive object, reading the property automatically returns its .value. This is automatic unwrapping, which saves you from writing .value:
const count = ref(0);
const state = reactive({ count });
console.log(state.count); // 0; no state.count.value needed
state.count = 1; // Equivalent to count.value = 1
The reactive object's get trap checks whether the retrieved value is a ref and returns .value when appropriate; the set trap has corresponding handling. Templates also unwrap refs through their own rendering access mechanism. In ordinary JavaScript, directly accessing a ref requires .value.
reactive([ref(0)])[0] still returns the ref, so use .value to read it.🧱 ComputedRefImpl: Lazy Evaluation and Caching
With ref understood, computed is a natural next step. Why can a computed value do less work than a method called from a template?
A computed value wraps a getter. It waits until the value is read before evaluating, stores the result, and reuses it while its dependencies remain unchanged. Storing and reusing that result is caching.
computed returns an instance called ComputedRefImpl. This teaching model uses a boolean _dirty flag: true means the cached result needs recomputing. Creation sets the flag without running the getter. The getter is wrapped in a reactive effect, which records its reactive dependencies as described in article 4:
// Simplified conceptual model of packages/reactivity/src/computed.ts
class ComputedRefImpl {
constructor(getter) {
this._dirty = true; // The cached result needs recomputing
this._value = undefined; // Cached result
// Dependency changes mark the value dirty instead of recomputing immediately
this.effect = new ReactiveEffect(getter, () => {
if (!this._dirty) {
this._dirty = true;
// Notify consumers of this computed value
triggerRefValue(this);
}
});
}
}
Reading .value recomputes only when the flag is set; otherwise it returns the cache:
get value() {
// Register consumers, just as for a ref
trackRefValue(this);
// Run the getter only when dirty
if (this._dirty) {
this._dirty = false; // Clear the dirty flag
this._value = this.effect.run();
}
return this._value;
}
computed() likewise returns new ComputedRefImpl(getter) in this model. Lazy evaluation follows three rules:
- No computation at creation. The first
.valueread runs the getter. - Cache after evaluation. Store the result in
_valuefor subsequent reads. - Dependency changes invalidate the cache. Set
_dirtytotrueand wait until the next read to recompute.
Verify the caching behavior with this example, saved as a .js file and run with Node.js v22 in an environment providing ref and computed:
let calls = 0;
const count = ref(1);
// computed evaluates once while dependencies remain unchanged
const double = computed(() => {
calls++;
return count.value * 2;
});
double.value; // First read evaluates the getter; calls = 1
double.value; // Cached result; calls remains 1
double.value; // Cached result; calls remains 1
Three reads perform one calculation. Calling an ordinary getDouble() method three times executes it three times. The difference matters for expensive calculations read frequently.
⚡ Comparing computed with Vue 2
If you studied computed in the Vue 2 source code course, the principle is the same: dirty flag + cache + lazy evaluation. Lazy evaluation means computing only when needed. Vue 2 uses a Watcher with a dirty flag; the simplified Vue 3 model here uses ReactiveEffect and _dirty, alongside the shared dependency-tracking and triggering mechanisms. Understanding one makes the other easier to follow.
❓ Questions and Answers
Q1: Why do refs in templates not need .value?
Template rendering automatically unwraps top-level refs. Refs used as reactive object properties are also unwrapped. Direct ref access in ordinary JavaScript does not have that handling, so you must write .value.
Q2: Why can destructuring a ref lose reactivity?
const { value } = countRef reads the current value into a separate variable. For a primitive, that variable no longer accesses the ref. To keep reactive object properties connected when destructuring, use toRefs or toRef, which provide connected ref objects rather than extracted primitive values.
Q3: Why does computed cache results while methods do not?
The computed model maintains a _dirty flag and _value cache. If dependencies are unchanged, it returns the previous result. A method executes afresh on every call. Use computed for derived state and methods when arguments or fresh execution are required.
Q4: Can I assign to a computed value?
By default, a getter-only computed value is readonly; assignment produces a development warning. If needed, use the writable form computed({ get, set }), though it is less common in everyday code.
Q5: How should I choose between ref and reactive?
Use ref for primitives; either can hold objects. Some teams use ref consistently to simplify conventions around .value and pass refs between functions without losing their reactive connection. Review the reactivity section of the Vue 3 course for details.
🧪 Exercise
Complete MyRef without looking up the implementation. Reading .value should log Dependency tracked. Assigning a changed value should log Update triggered; assigning an unchanged value should log nothing. Save as a .js file and run with Node.js v22.
class MyRef {
constructor(value) {
this._value = value;
}
get value() {
// Your code here: log 'Dependency tracked', then return this._value
}
set value(newVal) {
// Your code here: update _value and log 'Update triggered' only if changed
}
}
const count = new MyRef(0);
// Expected tracking/update messages:
// Dependency tracked
// Update triggered
// Dependency tracked
console.log(count.value);
count.value = 1;
count.value = 1; // Unchanged: this assignment should not log anything
console.log(count.value);
For an extra challenge, follow the ComputedRefImpl model to write myComputed(getter). Repeated reads with unchanged dependencies should run the getter only once. What additional flag do you need?
🎉 You now understand the mechanisms behind ref and computed! With reactive values and dependencies in place, how are updates scheduled? Next, we will explore the scheduler and nextTick to see how Vue 3 combines several changes into one update.
