Writing a state management library in 50 lines of JavaScript
Julien Verneaut
Posted on August 23, 2024
State management is one of the most important part of a web application. From the use of global variables to React hooks to the use of third-party libraries like MobX, Redux or XState to name just these 3, it is one of the topics that fuels the most discussions as it is important to master it to design a reliable and efficient application.
Today, I propose to build a mini state management library in less than 50 lines of JavaScript based on the concept of observables. This one can certainly be used as-is for small projects, but beyond this educational exercise I still recommend you to turn to more standardized solutions for your real projects.
API Definition
When starting a new library project, it is important to define what its API could look like from the beginning in order to freeze its concept and guide its development before even thinking about technical implementation details. For a real project, it is even possible to begin writing tests at this time to validate the implementation of the library as it is written according to a TDD approach.
Here we want to export a single class that we will call State
that will be instantiated with an object containing the initial state and a single observe
method that allows us to subscribe to state changes with observers. These observers should only be executed if one of their dependencies has changed.
To change the state, we want to use the class properties directly rather than going through a method like setState
.
Because a code snippet is worth a thousand words, here's what our final implementation might look like in use:
const state = new State({
count: 0,
text: '',
});
state.observe(({ count }) => {
console.log('Count changed', count);
});
state.observe(({ text }) => {
console.log('Text changed', text);
});
state.count += 1;
state.text = 'Hello, world!';
state.count += 1;
// Output:
// Count changed 1
// Text changed Hello, world!
// Count changed 2
Implementing the State class
Let's start by creating a State class that accepts an initial state in its constructor and exposes an observe method that we will implement later.
class State {
constructor(initialState = {}) {
this.state = initialState;
this.observers = [];
}
observe(observer) {
this.observers.push(observer);
}
}
Here we choose to use an internal intermediate state
object that will allow us to keep the state values. We also store the observers
in an internal observers array that will be useful when we complete this implementation.
Since these 2 properties will only be used inside this class, we could declare them as private with a little syntactic sugar by prefixing them with a # and adding an initial declaration on the class:
class State {
#state = {};
#observers = [];
constructor(initialState = {}) {
this.#state = initialState;
this.#observers = [];
}
observe(observer) {
this.#observers.push(observer);
}
}
In principle this would be a good practice, but we will use Proxies in the next step and they are not compatible with private properties. Without going into detail and to make this implementation easier, we will use public properties for now.
Read data from the state object with a Proxy
When we outline the specifications for this project, we wanted to access the state values directly on the class instance and not as an entry to its internal state
object.
For this, we will use a proxy object which will be returned when the class is initialized.
As its name suggests, a Proxy allows you to create an intermediary for an object to intercept certain operations, including its getters and setters. In our case, we create a Proxy exposing a first getter that allows us to expose the state
object's inputs as if they belonged directly to the State
instance.
class State {
constructor(initialState = {}) {
this.state = initialState;
this.observers = [];
return new Proxy(this, {
get: (target, prop) => {
if (prop in target.state) {
return target.state[prop];
}
return target[prop];
},
});
}
observe(observer) {
this.observers.push(observer);
}
}
const state = new State({
count: 0,
text: '',
});
console.log(state.count); // 0
Now we can define an initial state object when instantiating State
and then retrieve its values directly from that instance. Now let's see how to manipulate its data.
Adding a setter to modify the state values
We added a getter, so the next logical step is to add a setter allowing us to manipulate the state object.
We first check that the key belongs to this object, then check that the value has indeed changed to prevent unnecessary updates, and finally update the object with the new value.
class State {
constructor(initialState = {}) {
this.state = initialState;
this.observers = [];
return new Proxy(this, {
get: (target, prop) => {
if (prop in target.state) {
return target.state[prop];
}
return target[prop];
},
set: (target, prop, value) => {
if (prop in target.state) {
if (target.state[prop] !== value) {
target.state[prop] = value;
}
} else {
target[prop] = value;
}
},
});
}
observe(observer) {
this.observers.push(observer);
}
}
const state = new State({
count: 0,
text: '',
});
console.log(state.count); // 0
state.count += 1;
console.log(state.count); // 1
We are now done with the data reading and writing part. We can change the state value and then retrieve that change. So far our implementation is not very useful, so let's implement observers now.
Implementing Observers
We already have an array containing the observers functions declared on our instance, so all we have to do is call them one by one whenever a value has changed.
class State {
constructor(initialState = {}) {
this.state = initialState;
this.observers = [];
return new Proxy(this, {
get: (target, prop) => {
if (prop in target.state) {
return target.state[prop];
}
return target[prop];
},
set: (target, prop, value) => {
if (prop in target.state) {
if (target.state[prop] !== value) {
target.state[prop] = value;
this.observers.forEach((observer) => {
observer(this.state);
});
}
} else {
target[prop] = value;
}
},
});
}
observe(observer) {
this.observers.push(observer);
}
}
const state = new State({
count: 0,
text: '',
});
state.observe(({ count }) => {
console.log('Count changed', count);
});
state.observe(({ text }) => {
console.log('Text changed', text);
});
state.count += 1;
state.text = 'Hello, world!';
// Output:
// Count changed 1
// Text changed
// Count changed 1
// Text changed Hello, world!
Great, we are now reacting to data changes!
Small problem though. If you've been paying attention this far, we originally wanted to run the observers only if one of their dependencies changed. However, if we run this code we see that each observer runs every time a part of the state is changed.
But then how can we identify the dependencies of these functions?
Identifying Function Dependencies with Proxies
Once again, Proxies come to our rescue. To identify the dependencies of our observer functions, we can create a proxy of our state
object, run them with it as an argument, and note which properties they accessed.
Simple, but effective.
When calling observers, all we have to do is check if they have a dependency on the updated property and trigger them only if so.
Here is the final implementation of our mini-library with this last part added. You will notice that the observers
array now contains objects allowing to keep the dependencies of each observer.
class State {
constructor(initialState = {}) {
this.state = initialState;
this.observers = [];
return new Proxy(this, {
get: (target, prop) => {
if (prop in target.state) {
return target.state[prop];
}
return target[prop];
},
set: (target, prop, value) => {
if (prop in target.state) {
if (target.state[prop] !== value) {
target.state[prop] = value;
this.observers.forEach(({ observer, dependencies }) => {
if (dependencies.has(prop)) {
observer(this.state);
}
});
}
} else {
target[prop] = value;
}
},
});
}
observe(observer) {
const dependencies = new Set();
const proxy = new Proxy(this.state, {
get: (target, prop) => {
dependencies.add(prop);
return target[prop];
},
});
observer(proxy);
this.observers.push({ observer, dependencies });
}
}
const state = new State({
count: 0,
text: '',
});
state.observe(({ count }) => {
console.log('Count changed', count);
});
state.observe(({ text }) => {
console.log('Text changed', text);
});
state.observe((state) => {
console.log('Count or text changed', state.count, state.text);
});
state.count += 1;
state.text = 'Hello, world!';
state.count += 1;
// Output:
// Count changed 0
// Text changed
// Count or text changed 0
// Count changed 1
// Count or text changed 1
// Text changed Hello, world!
// Count or text changed 1 Hello, world!
// Count changed 2
// Count or text changed 2 Hello, world!
And there you have it, in 45 lines of code we have implemented a mini state management library in JavaScript.
Going further
If we wanted to go further, we could add type suggestions with JSDoc or rewrite this one in TypeScript to get suggestions on properties of the state
instance.
We could also add an unobserve
method that would be exposed on an object returned by State.observe
.
It might also be useful to abstract the setter behavior into a setState
method that allows us to modify multiple properties at once. Currently, we have to modify each property of our state one by one, which may trigger multiple observers if some of them share dependencies.
In any case, I hope that you enjoyed this little exercise as much as I did and that it allowed you to delve a little deeper into the concept of Proxy in JavaScript.
Posted on August 23, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 9, 2024
October 24, 2024