Reactivity is one of Vue’s greatest features. It is also one of the most mysterious if you don’t know what it’s doing behind the scenes. Like, why does it work with objects and arrays and not with other things, like localStorage
?
Let’s answer that that question, and while we’re at it, make Vue reactivity work with localStorage
.
If we were to run the following code, we would see that the counter being displayed as a static value and not change like we might expect it to because of the interval changing the value in localStorage
.
new Vue({
el: "#counter",
data: () => ({
counter: localStorage.getItem("counter")
}),
computed: {
even() {
return this.counter % 2 == 0;
}
},
template: `<div>
<div>Counter: {{ counter }}</div>
<div>Counter is {{ even ? 'even' : 'odd' }}</div>
</div>`
});
// some-other-file.js
setInterval(() => {
const counter = localStorage.getItem("counter");
localStorage.setItem("counter", +counter + 1);
}, 1000);
While the counter
property inside the Vue instance is reactive, it won’t change just because we changed its origin in localStorage
.
There are multiple solutions for this, the nicest perhaps is using Vuex and keep the store value in sync with localStorage
. But what if we need something simple like what we have in this example? We have to take a dive in how Vue’s reactivity system works.
Reactivity in Vue
When Vue initializes a component instance, it observes the data
option. This means it walks through all of the properties in data and converts them to getters/setters using Object.defineProperty
. By having a custom setter for each property, Vue knows when a property changes, and it can notify the dependents that need to react to the change. How does it know which dependents rely on a property? By tapping into the getters, it can register when a computed property, watcher function, or render function accesses a data prop.
// core/instance/state.js
function initData () {
// ...
observe(data)
}
// core/observer/index.js
export function observe (value) {
// ...
new Observer(value)
// ...
}
export class Observer {
// ...
constructor (value) {
// ...
this.walk(value)
}
walk (obj) {
const keys = Object.keys(obj)
for (let i = 0; i < keys.length; i++) {
defineReactive(obj, keys[i])
}
}
}
export function defineReactive (obj, key, ...) {
const dep = new Dep()
// ...
Object.defineProperty(obj, key, {
// ...
get() {
// ...
dep.depend()
// ...
},
set(newVal) {
// ...
dep.notify()
}
})
}
So, why isn’t localStorage
reactive? Because it’s not an object with properties.
But wait. We can’t define getters and setters with arrays either, yet arrays in Vue are still reactive. That’s because arrays are a special case in Vue. In order to have reactive arrays, Vue overrides array methods behind the scenes and patches them together with Vue’s reactivity system.
Could we do something similar with localStorage
?
Overriding localStorage
functions
As a first try, we can fix our initial example by overriding localStorage methods to keep track which component instances requested a localStorage
item.
// A map between localStorage item keys and a list of Vue instances that depend on it
const storeItemSubscribers = {};
const getItem = window.localStorage.getItem;
localStorage.getItem = (key, target) => {
console.info("Getting", key);
// Collect dependent Vue instance
if (!storeItemSubscribers[key]) storeItemSubscribers[key] = [];
if (target) storeItemSubscribers[key].push(target);
// Call the original function
return getItem.call(localStorage, key);
};
const setItem = window.localStorage.setItem;
localStorage.setItem = (key, value) => {
console.info("Setting", key, value);
// Update the value in the dependent Vue instances
if (storeItemSubscribers[key]) {
storeItemSubscribers[key].forEach((dep) => {
if (dep.hasOwnProperty(key)) dep[key] = value;
});
}
// Call the original function
setItem.call(localStorage, key, value);
};
new Vue({
el: "#counter",
data: function() {
return {
counter: localStorage.getItem("counter", this) // We need to pass 'this' for now
}
},
computed: {
even() {
return this.counter % 2 == 0;
}
},
template: `<div>
<div>Counter: {{ counter }}</div>
<div>Counter is {{ even ? 'even' : 'odd' }}</div>
</div>`
});
setInterval(() => {
const counter = localStorage.getItem("counter");
localStorage.setItem("counter", +counter + 1);
}, 1000);
In this example, we redefine getItem
and setItem
in order to collect and and notify the components that depend on localStorage
items. In the new getItem
, we note which component requests which item, and in setItems
, we reach out to all the components that requested the item and rewrite their data prop.
In order to make the code above work, we have to pass on a reference to the component instance to getItem
and that changes its function signature. We also can’t use the arrow function anymore because we otherwise wouldn’t have the correct this
value.
If we want to do better, we have to dig deeper. For example, how could we keep track of dependents without explicitly passing them on?
How Vue collects dependencies
For inspiration, we can go back to Vue’s reactivity system. We previously saw that a data property’s getter will subscribe the caller to the further changes of the property when the data property is accessed. But how does it know who made the call? When we get a data
prop, its getter function doesn’t have any input regarding who the caller was. Getter functions have no inputs. How does it know who to register as a dependent?
Each data property maintains a list of its dependents that need to react in a Dep class. If we dig deeper in this class, we can see that the dependent itself is already defined in a static target variable whenever it is registered. This target is set by a so-far-mysterious Watcher class. In fact, when a data property changes, these watchers will be actually notified, and they will initiate the re-rendering of the component or the recalculation of a computed property.
But, again, who they are?
When Vue makes the data
option observable, it also creates watchers for each computed property function, as well as all the watch functions (which shouldn’t be confused with the Watcher class), and the render function of every component instance. Watchers are like companions for these functions. They mainly do two things:
- They evaluate the function when they are created. This triggers the collection of dependencies.
- They re-run their function when they are notified that a value they rely on has changed. This will ultimately recalculate a computed property or re-render a whole component.
There is an important step that happens before watchers call the function they are responsible for: they set themselves as target in a static variable in the Dep class. This makes sure the they are registered as dependent when a reactive data property is accessed.
Keeping track of who called localStorage
We can’t exactly do that because we don’t have access to the inner mechanics of Vue. However, we can use the idea from Vue that lets a watcher set the target in a static property before it calls the function it is responsible for. Could we set a reference to the component instance before localStorage
gets called?
If we assume that localStorage
gets called while setting the data option, then we can hook into beforeCreate
and created
. These two hooks get triggered before and after initializing the data
option, so we can set, then clear, a target variable with a reference to the current component instance (which we have access to in lifecycle hooks). Then, in our custom getters, we can register this target as a dependent.
The final bit we have to do is make these lifecycle hooks part of all our components. We can do that with a global mixin for the whole project.
// A map between localStorage item keys and a list of Vue instances that depend on it
const storeItemSubscribers = {};
// The Vue instance that is currently being initialised
let target = undefined;
const getItem = window.localStorage.getItem;
localStorage.getItem = (key) => {
console.info("Getting", key);
// Collect dependent Vue instance
if (!storeItemSubscribers[key]) storeItemSubscribers[key] = [];
if (target) storeItemSubscribers[key].push(target);
// Call the original function
return getItem.call(localStorage, key);
};
const setItem = window.localStorage.setItem;
localStorage.setItem = (key, value) => {
console.info("Setting", key, value);
// Update the value in the dependent Vue instances
if (storeItemSubscribers[key]) {
storeItemSubscribers[key].forEach((dep) => {
if (dep.hasOwnProperty(key)) dep[key] = value;
});
}
// Call the original function
setItem.call(localStorage, key, value);
};
Vue.mixin({
beforeCreate() {
console.log("beforeCreate", this._uid);
target = this;
},
created() {
console.log("created", this._uid);
target = undefined;
}
});
Now, when we run our initial example, we will get a counter that increases the number every second.
new Vue({
el: "#counter",
data: () => ({
counter: localStorage.getItem("counter")
}),
computed: {
even() {
return this.counter % 2 == 0;
}
},
template: `<div class="component">
<div>Counter: {{ counter }}</div>
<div>Counter is {{ even ? 'even' : 'odd' }}</div>
</div>`
});
setInterval(() => {
const counter = localStorage.getItem("counter");
localStorage.setItem("counter", +counter + 1);
}, 1000);
The end of our thought experiment
While we solved our initial problem, keep in mind that this is mostly a thought experiment. It lacks several features, like handling removed items and unmounted component instances. It also comes with restrictions, like the property name of the component instance requires the same name as the item stored in localStorage
. That said, the primary goal is to get a better idea of how Vue reactivity works behind the scenes and get the most out of it, so that’s what I hope you get out of all this.