Why localStorage is not reactive

When Vue initializes a component instance, it observes the data option by walking through every property and converting it into a getter/setter pair with Object.defineProperty. The custom setter lets Vue detect a change and notify dependents; the getter lets Vue record who accessed the property — a computed property, a watcher function or a render function. localStorage gets none of this: it is not an object with properties that Vue can walk.

Arrays are the exception that proves the rule. Getters and setters cannot be defined on them either, so Vue instead overrides and patches array methods to wire them into the reactivity system. The question this raises is whether something similar can be done for localStorage.

A first attempt

Consider the following: an interval writes to localStorage, but the displayed counter stays static even though the counter property in the Vue instance is itself reactive. Changing the origin in localStorage simply does not move it.

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);

The nicest general solution is Vuex, keeping the store in sync with localStorage, but the example here calls for something simpler. A first try at fixing it directly is to override the localStorage methods so that components depending on an item can be tracked and notified.

// 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);

The redefined getItem records which component requested which item; the redefined setItem reaches out to every component that requested that item and rewrites its data prop. The trade-offs are immediate: a reference to the component instance must be passed into getItem, which changes its signature, and the function can no longer be an arrow function or the correct this value is lost.

How Vue tracks dependents

To avoid passing dependents explicitly, it helps to understand how Vue performs the tracking itself. Each data property keeps a list of dependents in a Dep class. The getter takes no input about its caller, yet when a dependency is registered, that dependent is already stored in a static target variable on Dep; it is set by the Watcher class. When the property changes, it is the watchers that get notified and trigger re-rendering or recalculation.

Watchers are created alongside everything that must react: each computed property function, each watch function (not to be confused with the Watcher class) and the render function of every component instance. They do two things:

  1. They evaluate their function on creation, which triggers dependency collection.
  2. They re-run the function when notified that a value they rely on has changed, recalculating a computed property or re-rendering a component.

Crucially, before calling the function, a watcher sets itself as the target in the static Dep variable, so any reactive property accessed during that call registers it as a dependent.

Setting a target from lifecycle hooks

Vue's internals are not accessible from the outside, but the mechanism can be imitated. If localStorage is assumed to be called while the data option is being set, the beforeCreate and created hooks — fired before and after fine data initialization — can serve as the point where a target variable is set to the current component instance (available in lifecycle hooks) and then cleared. The custom getters then register that target as a dependent.

To apply this to every component, the hooks go into a global mixin.

// 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;
  }
});

With that in place, the initial example produces a counter that increments 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);

Limits of the experiment

This is primarily a thought experiment rather than a complete solution. It does not handle removed items or unmounted component instances, and it requires the property name on the component instance to match the name of the item stored in localStorage. Its value is in showing how Vue's reactivity works behind the scenes and how far that knowledge can be pushed.