Redux, The Ultimate State Management Library For JavaScript

Priyanshu Saraf
Clever Programmer
Published in
10 min readOct 13, 2020

Hello everyone! Today we are going to discuss about Redux and why is it such an important tool for web development.

Are you excited?

So without any further delay, lets start!

What Is Redux?

Redux is a state management library for JavaScript applications. Redux is one of those skills which can make a BIG difference in your income. It can be used with react, angular, vue, or even vanilla JS. Because its just a state management library, it does not matter which framework you use for your front end. Now, the main reason why we need a state management tool like Redux is keeping different parts of our UI in sync. Let’s say you build an e-commerce application like an amazon clone, you want the cart to be updated as soon as the user clicks on the “Add To Cart” button. And for knowing more about the amazon clone, click here .

Lets deep dive into what I mean by keeping the different UI in sync.

Basically, what we want is a really good user experience. So, as soon as the user changes or interacts with one part of the UI, we want some other part of our UI to interact accordingly. We do not want there to be any sorts of delay, and this is where state management comes in. In more complex scenarios, when your UI is dependent on the interactions with the network requests, you might have to write a lot of code and there might be some really weird interactions with the data flow. You might have problems in these situations. Some of them could be unpredictable change of data or why is the data not flowing at all. Sometimes what might even happen is that you are stuck in an infinite loop which you cannot break easily.

Another problem which you might face is going to be prop drilling. This is a case where you find the data to be passed from the main component down to the very last component of your application. For example, in the below given diagram:

We see how the data from the parent component “app” passes all the way down to the sign up/sign in/cart. Now, this is not an ideal state management system, and whenever you find your data to be passed through multiple components, that’s called prop drilling.

The continuous passing of data from one component to another without a good design and management system is what we call prop drilling.

You never want to be stuck in this situation. You are basically adding more cache to your site and also, this makes the entire architecture of your site look miserable.

If you have ever faced any problems like this, its an indication that you need to use a state management tool. There are various tools for this purpose. Some of them are:

  • Flux- Facebook came up with a solution to the state management using a tool called flux.
  • Redux- Redux was inspired by Flux, but has grown more because of its simpler structure and code.
  • Mobx- This is another really popular tool for state management, and is ideal for smaller applications.

Today, we will discuss more about Redux.

Redux can be thought of like a store house of state management. So, instead of storing the state management in all different places of the UI, there is a single store house in which the entire application’s state is stored. The advantage of such a structure of state management is that there is only 1 store to make a request to if a component has to change its state. In the amazon clone’s example, well, whenever the user clicks the “Add to cart” button, there is a request made to only a single database or storehouse and so, this solves the problem of complex state management and makes it really easy and quick.

This was about state management, but the advantage of using Redux is that it lets you know how, why, when, and where the state management went wrong if the data flow does not behave as anticipated.

Lets discuss a few pros and cons to Redux.

Pros to Redux:

  • Makes predictable state changes
  • Centralized state (store house)
  • Easy debugging through Redux Dev Tools
  • Preserves page state (the page’s cache is not reloaded every time the user navigates somewhere else)
  • Undo and Redo ability through Redux Dev Tools
  • Works with any library/frameworks
  • Ecosystem of add on’s

Cons of Redux:

  • Quite complex
  • Verbose code

When NOT to use Redux:

  • If you are on a budget
  • If you are not making large applications
  • If you hardly have any data flow or state management
  • If you do not have any dynamic data

With the explanations done, lets jump in and start off by setting up the development environment with react JS and Redux.

In this blog, we are going to start with the latest version of Redux which already gives us a lot of boiler plate code. Mostly, we will be using react along with Redux, but you can implement Redux wherever you wish to.

To get started, enter the following command in your command prompt:

npx create-react-app my-app --template redux

What this does is basically give you a really good template to start off with Redux, and already comes with a lot of boilerplate code which might have taken you a lot of time to write. Now, lets see the road map for you to learn Redux in the best manner while the template is getting set up:

Your Road Map For Becoming A Master At Redux:

As we have discussed earlier, Redux plays a lot of importance in state management and is useful for escaping prop drilling. If you take it the react way, then you should probably start off with React Context API. This is essentially a tool for state management which comes in with react, and there is barely any set up required to get this up and running. This is one more reason why I love react, and why you should use it in projects. React already has a very light weight tool for state management called react context API. Lets look at what are the advantages of using it:

  • Lightweight: this is way more light weight than Redux, and hence is suggested for light weight products and for very basic/intermediate projects which are light weight by default.
  • Does not require much set up: React context API hardly requires any prior set up, except for your react project. You can literally completely set it up in minutes if you become really good at it
  • There are several use cases of it, and if you find your client demanding for a very simple project, which might require state management, then the context API is for you.
  • The concepts of state management which you will learn from the context API are basically the same for Redux, only Redux is preferred for heavy weight and large scale applications.

Of course, React Context API is something which is limited to react, and so, we do not cover the principles of the context API in this blog. Nevertheless, the context API is enough powerful to power a large scale application too, although the limitation to react is where the trouble is. Although, if you do specialize in react and are interested to check out the blog regarding the context API in more depth, click here.

After learning react context API, I would highly recommend you to give Redux a shot and continue with this blog. Even if you have not checked it out, do not worry.

By now, I am hoping that your react app has been set up, and then you should see the following command in your command line:

happy hacking!
>

If everything went well, and if you were able to set this up, then congratulations! you can proceed with the blog.

Lets move on and now, you can enter the following command in your command line:

npm start 

What this basically does is that it spins up the entire application and now, a browser window should open up and show something like this:

You can play around with this as much as you want to, you can click on the “Add Async” or the “Add Amount” buttons, and you can do some really cool stuff with this. But what we are interested in is the code. So lets jump into it.

If you get inside of Counter.js, you will see a bunch of code running around and you might be overwhelmed with all this.

Do not worry.

The code might look really complex, although in reality, it is not. It is written in a really clean way, and you can very easily understand it if you pay close attention. Do not worry if you cannot. Its okay.

If you want to, you can simply remove the following files from your folder: logo.svg, App.test.js and setupTest.js . These are some files which we never really use, and do not worry, we can still continue on. If you come to index.js, you’ll see the following code:

<Provider store={store}>
<App />
</Provider>

What we get to know from this block of code is that the Provider surrounds the entire app. This is basically the one and only data layer which we talked about earlier that wraps the entire website for managing the state.

Coming inside of the store.js file, we see the following code:

import { configureStore } from "@reduxjs/toolkit";
import counterReducer from '../features/counter/counterSlice';
export default configureStore ({
reducer : {
counter: counterReducer,
}
});

The code in the store is quite simple. The code is also quite clean, and there is not really much to it.

Basically, we have a tool kit which Redux provides us with, and we are exporting a configureStore from it. Inside of this configureStore, we are parsing in a reducer, which has a counter which is the counterReducer.

Imagine Redux and the entire data layer to be one giant layer, inside of which we have the app component. Well, another reason why Redux is quite cool is that we can have several different layers! Think of it as layers of an onion. So, in a way, you can have several store layers! Now, this might bring up a really good question — Why would we want several layers? Now, the main head layer could hold the user stuff. Think of it like the userLayer for now. Now, inside of this user layer, we could have a layer called the basketLayer. So in the userLayer, we would only have the stuff related to the user, ex- authentication, etc-. But inside of the basketLayer, we can have all the stuff related to the basket, for example, add to basket, remove from basket, etc-. Now, in this structure, the user would have his own reducer, and the basket would have its own reducer. The below given diagram might help you understand the concepts which I am talking about in depth:

These layers are what we call “Slices”. The main userLayer could be called as 1 slice of the entire store, and the basketLayer would be another slice of the store.

NOTE: The layers are all independent in nature. The user layer does not affect the basket layer, and vice versa. The main reason for them being isolated components is for reduction in complexity. Also, DO NOT CONFUSE between these layers and the components. This is just a concept which I am trying to explain in a visual way.

If you go inside of the counterSlice.js, you’ll see some code like such:

export const counterSlice = createSlice({name: 'counter',initialState: {value: 0,},reducers: {increment: state => {// Redux Toolkit allows us to write "mutating" logic in reducers. It// doesn't actually mutate the state because it uses the Immer library,// which detects changes to a "draft state" and produces a brand new// immutable state based off those changesstate.value += 1;},decrement: state => {state.value -= 1;},incrementByAmount: (state, action) => {state.value += action.payload;},},});export const { increment, decrement, incrementByAmount } = counterSlice.actions;

Here, we see that we are exporting a counterSlice which has a name of “counter” , and it also has an initial state of 0.

Inside of the increment and the decrement functions, we basically get the functionality of reducing or incrementing a number in the boilerplate code, and we export this inside of the export const counterSlice.actions line.

This blog was to give you a basic explanation of Redux and its architecture. Every time the implementation of it might differ, so I highly recommend that you check out the clones and learn from there by pattern recognition, or check out the official documentation.

A major thing that I wanted from this blog was for me to be able to explain you guys how Redux works, why we need it, but of course, it is a huge topic. So what I recommend doing is going to the official documentation of Redux here. You will find a tremendous amount of value in this and reading the official documentation is always a good way to get started with anything new.

That’s gonna be it for this blog.

Thank You! I hope you enjoyed it!

Priyanshu Saraf

--

--

Priyanshu Saraf
Clever Programmer

Blogger, freelancer, and Tutor! Let’s connect on instagram! Here’s my handle: @saraf_priyanshu_