Approach to build our own Redux Store

Sourav Singh
3 min readJan 28, 2020

--

Ever wondered, how Dan would have implemented the Redux Store. He is a person I admire totally when it comes to his JS skills.

PS: I have not seen the real implementation of Redux store. This is just an approach/mental model you can give if someone asks this in an interview. This is actually a Microsoft interview question.

Let’s go through the flow of redux.

Observations :
A global Data store which can store data in form of Object tree.

Our UI Components should be able to subscribe to a event to re-render itself when something in the store changes.

So, approach that should strike the mind is an Observer pattern. Where Store is the observable and our React Components are Observers.

Now the problem has become overwhelming.

According to react-redux api, Our store should have following methods :

subscribe(callback) : The callback should be registered with the store so that it can be called whenever the store state changes. Our store should have a subscribedEvents Queue to store all the callbacks.

getState(): Returns the state of the store.

dispatch() : Place where the actions are passed to reducers and reducers are run. This is the place where the subscribed callback is run. This is how it should be “ We will run the callback to notify our Components whenever someone dispatches an action. My component would have the logic of deciding whether it should actually re-render or not.

Let’s have our simple version of createStore function which accepts reducers and forms a global Store with all its methods like subscribe, getState and dispatch.

Now we have our store ready,

Remember the connect function of react-redux. We can subscribe to the store data inside this function. The core question is that how is my Component gonna know when to re-render.

We can have a method which runs mapStateToProps when something in the store changes and shallow compares the result with old result of mapStateToProps. If there is any change then , call forceUpdate() to re-render the component.

connect returns a function which accepts a Component and returns an enriched component. I have written a sample implementation for connect. Go through it especially the re-rendering logic.

Our component can now easily subscribe and update itself once we have our connect function ready.

This is why we use it, connect(mapStateToProps,mapDispatchToProps)(Component).

So , now we know the mental model of how react-redux might be working. Remember the exact implementation by Dan Abramov would be more complex to support a lot of overwhelming features like middlewares etc.

Thanks for reading.. :)

--

--

Sourav Singh
Sourav Singh

Written by Sourav Singh

Software Engineer @Amazon, Prime Video | Previously at Disney+Hotstar

No responses yet