Writing a state management library in lines of JavaScript
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.
The above is the detailed content of Writing a state management library in lines of JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.
