How to Create State Management Library From Scratch(Node.js)

Salih İsa Uçar
6 min readNov 22, 2020

Nowadays, most of us are using some state management library to manage our application state. Basically, When someone says about handling some application’s state problem, I think the first thing that comes to our mind is redux. When we briefly look at the redux, We are going to realize that it has 3 important concepts which consist of action, reducer, and store.

Basic redux lifecycle

As you see in the demonstration about redux, We have a view where our data is showed and action is triggered by the view(App client) after that reducer gets the action and decides what will happen. All this process is for updating our app store where we put our variable that is commonly used by our app.

Sounds good right. When you think of all those processes like getting data, updating them, and saying the view ok all done is kind of convoluted but it is not :) All system is based on observer pattern. The observer pattern is a software design pattern in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods.

I think it is time to code something :) I have babbled enough about some redux stuff :) before we deep dive into codding, we have to understand the observer pattern(sometimes, it can be named subscriber pattern but it is the same thing :)). Let's open the VS Code.

module.exports = class TeacherPublisher {
constructor() {
this.observers = [];
this.information = "";
}
subscribe(subscriber) {if (this.observers.indexOf(subscriber) == -1) {
this.observers.push(subscriber);
}
}
ChangeInformation(newInfo) {
this.information = newInfo;
this.notify(this.information);
}
notify(info) {for (var i = 0; i < this.observers.length; i++) {
this.observers[i].GetInformationFromTeacher(info);
}
}
};

I have created a teacher.js to notify my message to students. This class has an observers array where I planned to hold my subscribers. ChangeInformation method is the main method that notifies the subscribers that are in the observers variable when something is changed. It is time to create a student.js

module.exports = class Student {constructor() {}GetInformationFromTeacher(data) {console.log(`Teacher changed someting :) data : ${data}`);}};

The Student class has just a method which is going to be fired by The Teacher class. Let’s see how we can interact with them. I am going to create an app.js

var Teacher = require("./teacher");
var Student = require("./student");
var T = new Teacher();
var S = new Student();
T.subscribe(S);
T.ChangeInformation("The lesson will be tomorrow at 10 am");

As you see, The student class has been subscribed to the teacher class which means that the student is listening to the teacher. When you run app.js you will see this message.

node app.js
Teacher changed someting :) data : The lesson will be tomorrow at 10 am

Let’s embark upon the new state management journey because we have mentioned how the pub-sub pattern works.

I have 3 folder components, Library, and store. As you think, I am going to place my app components in the component folder. That folder is for the developer who develops the app but other folders are the core folder for this tutorial. I want to start with the store folder and pick store.js up.

Having a reducer for the store is to fire the state change process. When you look at the dispatch method it accepts action and payload to convey them to the reducer. But the most important part is StorePublisher. I will come back to clarify why We need this class. Now, I am going to create reducer.js

So simple it gets the action type and does something depends on the action type. As you can imagine actionTypes.js is just holding types. Let’s create it.

It returns the type. You can put what you want. :) It is time to jump to actions.js that is responsible to handle and return new state value.

This method exactly was created arbitrarily. You can create some methods based on your business logic. It’s up to you :)

So far so good, Let’s a little bit talk about what we have just done. We have a store, a reducer, and action. When dispatch is triggered reducer gets the action which holds the action name after that, the reducer pushes the action method and says “Hey!! I have an acctionType and I think you can take care of it.” Action is fired by the reducer and returns a new state :)

Do you remember that I said we were going to come back to the StorePublisher class later? Now the StorePublisher class is being created. This class notifies the other class that listens to the Publisher. Just bring the case in front of your eyes. When you use the redux. You have some prop in a component and want the props are changed by the state manager. This publisher is in charge of distributing the new state. Enough talking :)

Ok. We have done it but we need the listeners which means the base component which subscribes the component to the publisher. Every component in the application must be derived from the base component. Because If you want to get a new state it is the way to get it :)

Subscribe method gets the object reference(the component that we will create soon) and sent it to the publisher. Before I forget to mention the observer array, we have to create observerArray.js to hold observer referance

After a lot of preparation, We are ready to build our first component. Don’t forget the component must be derived from the base-component.

Just take a closer look at the mapStateToProps method. It is our key to get a changed state :) This method will be triggered by the Publisher.

publish(state) {
console.log("publish was run");
for (var i = 0; i < observers.length; i++) {observers[i].mapStateToProps(state);}
}

This is the key :) I assume that You could understand why the store has a publisher :) When you run the “changeStore” in our component. The store says “Hey somebody changed something. Do not sleep, Publisher. Take care of them” :) After that publisher gathers his subscribers and tells them “Hey something happens and I have this information. Take it :)” let's create a second component :)

Woow!! I am getting tired of typing but There are a few remaining steps to complete this article :) It’s time to combine all of them. I am going to show you how we can interact with them. For this index.js helps us :) Let’s do it

In order to publish the state to my component, I have created a store object that gets a reducer. Now I am giving the store to my component. Do not forget When I create my component, the base component automatically informs the publisher “Hey!! we have a new guest :)”. At that point, my store knows reducer and publisher, my publisher knows its subscribers. All we have to do is just fire the ChangeStore method :)

As you see when we change the store from “firstComponent”, Aoutomatlcy, “secondComponent” was updated. :) Actually, This is All That what I have been trying to explain :)

If you have any questions, Don’t hesitate, I am here to answer. I hope that everything happens what you expect.

GitHub link for this:https://github.com/salihisaucar/StateManagement

Salih Isa Ucar :)

--

--