cft
Become a CreatorSign inGet Started

Let’s build our own Redux

Well, you’re at the right place and wonder no more, today when you’ll leave you’d have sufficient knowledge to build your own redux.


user

Shivam Bhasin

4 months ago | 4 min read
Follow

lets-build-own-redux-mgmkz

I coded in Java/Kotlin for most of my college life, and hence, followed the MVC pattern mostly for projects.

Ironically, my first job right after college was as a ReactJS developer. Now that I had to shift my paradigm from that to the functional approach of modeling data, Redux, it wasn’t easy for me and, I had my share of tough times getting my head around.

For starters, it was almost like magic. How is redux putting all the pieces together was the question that haunted me for a long time until one day I decided not anymore. The geek inside me, just like yours, started getting to know it more.

Well, you’re at the right place and wonder no more, today when you’ll leave you’d have sufficient knowledge to build your own redux.

Redux, minimally, can be broken down into two things — reducers and flux.

What is flux?

Flux is a pattern or architecture, not a library or framework, for managing data flow in our applications. Created by Facebook, now Meta, its USP is that data flows in one and only one direction. See the image below.

Image source: https://github.com/facebook/flux/tree/main/examples/flux-concepts

Any change in the data, i.e. the store, will have to go through the dispatcher. That prevents more than one action from changing the same data in the store at the same time. Views read any required information from the store and display it on the UI part. Let’s understand these quickly using a simple add-to-cart functionality in our application.

Dispatcher

The only source of incoming to the store is through the dispatchers. The dispatcher receives information through actions and passes it to the store. Every store will receive every action. Also, the flux pattern states that every application should have a singleton dispatcher.

As soon as the user presses the add-to-cart button, our view captures the event and dispatches an add-to-cart action containing the product id.

Store

The store is the mini database of our application. It has all the data that is needed to persist and that’s it. It registers with the dispatcher to receive actions. The data in the store must only be mutated by responding to an action.

On receiving the add-to-cart action, our store updates the cart and emits a change event in our application.

Actions

Actions are simple JavaScript objects with the type of action that needs to be dispatched and the payload, or data required for that particular action. Conventionally, actions should be semantic and not describe the implementation of the action.

In our case add-to-cart is the action which will look more or like below.

{

type: 'add-to-cart',

payload: {

product: '1'

}

}

Views

These are just UI components that display data from the store. They listen to change events from the store and re-render depending on the context. Actions are typically dispatched from the UI on user-triggered event callbacks.

When the user presses the add-to-cart button, we dispatch the add-to-cart action on the onclick callback.

Now that we know the flux framework, let’s start with building our own redux. Also, if you have a lesser understanding of the reduce method of JavaScript, quickly give this piece a read and join back here. If you already know let's start with a simple sum function using reduce.

Reducing an array to sum

Reduce method can be used to calculate the sum of the array. Here’s a simple implementation.

const sum = (nums) => {

return nums.reduce((state, next) => state + next);

};

sum([1,2,3,4]); //

10

Let’s make this a bit more complex to write.

const sum = (nums) => {

const iterator = (state, next) => state + next;

const [initialState, rest] = nums;

return rest.reduce(iterator, initialState);

};

sum([1,2,3,4]); //

10

I just destructured the array and created the iterator function separately. Looks good till now. Now let’s try to move towards a more real-world-like application of this concept.

Getting specific

Suppose we have a cart that receives updates about the product quantity as per the user interaction on the UI. Here’s an updated version of the above code to match this use case.

The update method is the same sum function we saw before just used as an update method of the quantity of a product inside the cart. All values in the array passed to the update method are essentially actions passed to the reducer. Let’s make it more clear by giving names to our actions. See below code.

See how all our actions now have a type field and the payload, qty in our case. Also, passing the existing store as the initial state to reduce() then overwriting it with the result, we can start transforming data across multiple calls to reduce.

This approach makes our code easier to read and maintainable. Also, our store is only concerned with data modeling and logic which makes store and reducers extremely portable.

The same set of reducers and stores can be used for both, a web application on ReactJS and a mobile application on React Native which is pretty cool considering the less time we have nowadays to ship our idea to a product.

Hope you’ve learned something new today. Do try to make a redux-like application to solve an application challenge closer to you. Also, let me know what JavaScript topics are still haunting you and we’ll try to understand them.

Let the GEEK inside you win!

More content at plainenglish.io

Upvote


user
Created by

Shivam Bhasin

Follow

Engineer | Learner | Writer

Simplifying things since childhood. Writes about JavaScript, application development, and self-help.


people
Post

Upvote

Downvote

Comment

Bookmark

Share


Related Articles