Open Hours Mon - Fri: 8.00 am - 6.00 pm, IST

Redux Definition – Learn what is Redux

It is very stressful in maintaining the states or global variables across large JavaScript enterprise application. Example: if you want to know if a user is logged in with flag “isLoggedIn” across the screens it is not that easy unless you write garbage code everywhere to pull this variable.

Redux Definition

For JavaScript applications, Redux is a predictable state container. It enables you to create apps that operate consistently across client, server, and native platforms and are simple to test. Additionally, it offers a fantastic developer experience with features like live code editing and a time-traveling debugger. Redux solves the problem of accessing the states across the application. Redux is a open source library which can be used with many Web development frameworks like React, Angular, Vue.js or even Vanila JavaScript application. For large enterprise applications you can define Redux like a central repository which can be accessed across any part of the application making life simple especially Redux with react. It is more like a Session object/variable which can be accessed anywhere in the application. Let us start with the actual meaty part of this Redux tutorial.
Read also – React tutorial for beginners in 10 mins

Environment

For this tutorial below are the Redux devtools or SDK’s which I will be using.
  • Visual studio code – I love this editor. If you do not have one you can download from https://code.visualstudio.com/. You could even use Sublime or Atom.
  • Node js installed – You could even use Yarn. If you do not have Node js installed you can install it from here – https://nodejs.org/en/download/

Creating Redux tutorial project

I have created a folder Redux-Tutorial and in the terminal I will be initializing the project using the below command.
npm init --s
Once above step is done just verify your project is setup correctly by creating an index.js file and put a console.log statement. Once done just run the node command like below. You should see the console log output.
node index

Install Redux

Now that the project is setup correctly. It is time to install Redux using the following command.
npm install redux
redux definition

STAR – (Store, Action, Reducer)

We are all set with the environment for Redux tutorial. Before going on handson I want you to remember the below 3 jargons of Redux.
  • Store – Redux Store is a placeholder for all the states which you want to save. Imagine Store as in Amazon website an e-commerce store where you can purchase stuff.
  • Action – This is the type of transaction you want to do. It could be buy product or return product or even sell product.
  • Reducer – This piece of Redux is the one which does most of the action. Reducer in a way you can think that it reduces some collection based on the action/instruction passed to it.
I call the above jargon as STAR. Easy to remember, right? Every Javascript application which has redux implementation need to have all the components of STAR.
  • As part of this Redux tutorial I will be taking an online shopping(Amazon) as an example. We will name our Redux store as amazonStore.
  • The product we want to buy is a Shirt, so the action will be BUY SHIRT
  • The action will be passed on to a Redux reducer called placeShirtReducer.

Import Redux

First step for us is to import the redux library as below.
const redux=require('redux');
 

Define the inventory which Amazon has

//Define initial inventory
const initialInventory = {
    numOfShirts : 100
}
 

Define action buyShirt

Next we have to define what type of transaction we want to do .
//Define action
const BUY_SHIRT = 'BUY_SHIRT'
function buyShirt(){
    return{
        type:BUY_SHIRT
    }
}
 

Define Reducer function

Next we define how the store behaves when the “buyShirt” action is called.
//Define reducer
const buyShirtReducer= (inventory = initialInventory, action)=>{
    switch(action.type){
        case BUY_SHIRT: return{
                ...inventory,
                numOfShirts:inventory.numOfShirts-1
            }

        default  : return inventory
    }
}

Define Store

This is the last step. We creat the store with the list of reducer functions(buyShirtReducer) it has got.
//Define store
const amazonStore = redux.createStore(buyShirtReducer);

Testing

Now, that the definition of STAR is done. All that is left is to test out the code. You use the dispatch function to let the reducer know what action we need to perform.
//Initial inventory
console.log("Initial inventory", amazonStore.getState());

//Subscribe to change of inventory
amazonStore.subscribe(()=>console.log("Updated inventory", amazonStore.getState()));

// Buy shirt by passing buyShirt as a function
amazonStore.dispatch(buyShirt());
You can even call the dispatch method by passing the action JSON directly like below.
//Place order by directly passing action JSON
amazonStore.dispatch(
    {
        type:BUY_SHIRT
    }
);
The final code is here.
const redux=require('redux');

//Define initial inventory
const initialInventory = {
    numOfShirts : 100
}

//Define action
const BUY_SHIRT = 'BUY_SHIRT'
function buyShirt(){
    return{
        type:BUY_SHIRT
    }
}


//Define reducer
const buyShirtReducer = (inventory = initialInventory, action)=>{
    switch(action.type){
        case BUY_SHIRT: return{
                ...inventory,
                numOfShirts:inventory.numOfShirts-1
            }

        default  : return inventory
    }
}


//Define store
const amazonStore = redux.createStore(buyShirtReducer);

//Initial inventory
console.log("Initial inventory", amazonStore.getState());

//Subscribe to change of inventory
amazonStore.subscribe(()=>console.log("Updated inventory", amazonStore.getState()));

// Buy shirt by passing buyShirt as a function
amazonStore.dispatch(buyShirt());

//Place order by directly passing action JSON
amazonStore.dispatch(
    {
        type:BUY_SHIRT
    }
);

Add another action – Buy Pant

We will try to add some Pants also as part of the inventory and accommodate an action for “Buy Pant”. The modified code will look like below.
const redux=require('redux');

//Define initial inventory
const initialInventory = {
    numOfShirts : 100,
    numofPants : 100
}

//Define action
const BUY_SHIRT = 'BUY_SHIRT'
function buyShirt(){
    return{
        type:BUY_SHIRT
    }
}

const BUY_PANT = 'BUY_PANT'
function buyPant(){
    return{
        type:BUY_PANT
    }
}



//Define reducer
const buyShirtReducer = (inventory = initialInventory, action)=>{
    switch(action.type){
        case BUY_SHIRT: return{
                ...inventory,
                numOfShirts:inventory.numOfShirts-1
            }
        case BUY_PANT: return{
                ...inventory,
                numofPants:inventory.numofPants-1
            }

        default  : return inventory
    }
}


//Define store
const amazonStore = redux.createStore(buyShirtReducer);

//Initial inventory
console.log("Initial inventory", amazonStore.getState());

//Subscribe to change of inventory
amazonStore.subscribe(()=>console.log("Updated inventory", amazonStore.getState()));

// Buy shirt by passing buyShirt as a function
amazonStore.dispatch(buyShirt());

//Place order by directly passing action JSON
amazonStore.dispatch(buyPant());
The final output of the code should be like below.
As a coding guideline it is always better to split actions, reducers in separate folders.
Github source code – https://github.com/praneeth1984/LazyCoding/tree/master/redux-tutorial

Conclusion

Read also – React with Redux tutorial Before you define Redux in your project, you need to really think through if you really need Redux. If it is an application with 5 or 10 components I would recommend using Context and Hooks. The reason being Redux involves lot of boiler plate codes which is unnecessary for a small application. Happy Coding!

Leave a Reply