Understanding the core of modern Frontend frameworks is crucial for every web developer. Vue, known for its reactivity system, offers a seamless way to update the DOM based on state changes. But have you ever wondered how it works under the hood?
In this tutorial, we’ll demystify Vue’s reactivity by building our own versions of ref() and watchEffect(). By the end, you’ll have a deeper understanding of reactive programming in frontend development.
Before we dive in, let’s define reactivity:
Reactivity: A declarative programming model for updating based on state changes.1
This concept is at the heart of modern frameworks like Vue, React, and Angular. Let’s see how it works in a simple Vue component:
<script setup>
import { ref } from "vue";
const counter = ref(0);
const incrementCounter = () => {
counter.value++;
};
</script>
<template>
<div>
<h1>Counter: {{ counter }}</h1>
<button @click="incrementCounter">Increment</button>
</div>
</template>
In this example:
- State Management:
refcreates a reactive reference for the counter. - Declarative Programming: The template uses
{{ counter }}to display the counter value. The DOM updates automatically when the state changes.
To create a basic reactivity system, we need three key components:
- A method to store data
- A way to track changes
- A mechanism to update dependencies when data changes
- A store for our data and effects
- A dependency tracking system
- An effect runner that activates when data changes
An effect is a function that executes when a reactive state changes. Effects can update the DOM, make API calls, or perform calculations.
type Effect = () => void;
This Effect type represents a function that runs when a reactive state changes.
We’ll use a Map to store our reactive dependencies:
const depMap: Map<object, Map<string | symbol, Set<Effect>>> = new Map();
This function records which effects depend on specific properties of reactive objects. It builds a dependency map to keep track of these relationships.
type Effect = () => void;
let activeEffect: Effect | null = null;
const depMap: Map<object, Map<string | symbol, Set<Effect>>> = new Map();
function track(target: object, key: string | symbol): void {
if (!activeEffect) return;
let dependenciesForTarget = depMap.get(target);
if (!dependenciesForTarget) {
dependenciesForTarget = new Map<string | symbol, Set<Effect>>();
depMap.set(target, dependenciesForTarget);
}
let dependenciesForKey = dependenciesForTarget.get(key);
if (!dependenciesForKey) {
dependenciesForKey = new Set<Effect>();
dependenciesForTarget.set(key, dependenciesForKey);
}
dependenciesForKey.add(activeEffect);
}
When a reactive property changes, this function activates all the effects that depend on that property. It uses the dependency map created by the track function.
function trigger(target: object, key: string | symbol): void {
const depsForTarget = depMap.get(target);
if (depsForTarget) {
const depsForKey = depsForTarget.get(key);
if (depsForKey) {
depsForKey.forEach(effect => effect());
}
}
}
This creates a reactive reference to a value. It wraps the value in an object with getter and setter methods that track access and trigger updates when the value changes.
class RefImpl<T> {
private _value: T;
constructor(value: T) {
this._value = value;
}
get value(): T {
track(this, "value");
return this._value;
}
set value(newValue: T) {
if (newValue !== this._value) {
this._value = newValue;
trigger(this, "value");
}
}
}
function ref<T>(initialValue: T): RefImpl<T> {
return new RefImpl(initialValue);
}
This function creates a reactive computation. It executes the provided effect function and re-runs it whenever any reactive values used within the effect change.
function watchEffect(effect: Effect): void {
function wrappedEffect() {
activeEffect = wrappedEffect;
effect();
activeEffect = null;
}
wrappedEffect();
}
Let’s see our reactivity system in action:
const countRef = ref(0);
const doubleCountRef = ref(0);
watchEffect(() => {
console.log(`Ref count is: ${countRef.value}`);
});
watchEffect(() => {
doubleCountRef.value = countRef.value * 2;
console.log(`Double count is: ${doubleCountRef.value}`);
});
countRef.value = 1;
countRef.value = 2;
countRef.value = 3;
console.log("Final depMap:", depMap);

check out the full example -> click
While our implementation covers the core concepts, production-ready frameworks like Vue offer more advanced features:
- Handling of nested objects and arrays
- Efficient cleanup of outdated effects
- Performance optimizations for large-scale applications
- Computed properties and watchers
- Much more…
By building our own ref and watchEffect functions, we’ve gained valuable insights into the reactivity systems powering modern frontend frameworks. We’ve covered:
- Creating reactive data stores with
ref - Tracking changes using the
trackfunction - Updating dependencies with the
triggerfunction - Implementing reactive computations via
watchEffect
This knowledge empowers you to better understand, debug, and optimize reactive systems in your frontend projects.
-
What is Reactivity by Pzuraq ↩