Simplifying Redux

Simplifying Redux

If you are learning React or working on a project which uses React then you must have heard about Redux.

In this article, we will see

  • What is Redux?

  • What is state management?

  • Why use State management tools?
  • How Redux works?

What is Redux?

If we go by the official definition of the Redux from Redux docs it goes like "Redux is a predictable state container for JavaScript apps."
For beginners, the above definition is kind of confusing. Let me explain it in more detail.

Redux is a State Management library that we can use to Manage the state of the Application.

Now if you are new to React and Redux you might get a Question that What is State Management?

Let's see the quick explanation about the State

State can save the component’s dynamic data and determine the component’s behavior.

What is state Management and Why use State Management tools?

Suppose you are building an application like Amazon using React. React uses a component-based architecture approach. So there are different components in your UI and each component also contains a state of its own. You might have Auth state, cart state also product state, and categories state.

As the complexity of the project increases, it becomes very difficult to maintain the state. You will also come across a scenario where a user makes a change in one part of the UI the another part of the UI should immediately get updated. for example when the user clicks on Add to Cart button then the item should get updated on the cart screen as well.

In such scenarios, you have to keep the component in Sync because data flow from one component to another component. That's where a State Management tool like Redux makes our life easy.

Advantages of State Management.

  • The State Management tools help us to structure the application state.

  • With the help of state Management tool we can share the data across the components.

  • It makes data flow predictable

How Redux works and Solves the problem of state Management.

Redux stores all the applications state in one single place known as a Store

Redux stores all the applications state in the javascript object known as a Store. That's the single source of truth

Due to one central place for the state, there is no need for UI components to save the state on its own. Now if we want to update the data there is only a single space name Store from which component can access the state. It also helps us to keep all the UI components in Sync.

With the help of Redux we can also avoid prop drilling issues.

If there are deeply nested components in UI then we have to pass the state from the parent component to its child component and from there again we pass the state down to its child component. This Scenario is where we pass the state from parent to child in a deeply nested tree known as a prop drilling.

Main Pillars of Redux

There are three main Pillars in Redux

  • Store

  • Actions

  • Reducers

Redux is built on a Top of functional programming concepts. So it maintains the state of the entire application in an immutable javascript object.

Store

It's a plain javascript object in which we can save all the application states. It is immutable. Redux can have only a single store in your application.

It's a single source of truth for the state and accessible for all the UI components. It can contain anything like products, cart elements, categories, etc. We could have many slices of the state in the store.

 {

   products: [  ] , 
   cart: [  ] , 
   users: [  ]

}

One important thing to remember about the store is it's immutable. We can't directly change the state in the Store.

import { createStore } from "redux";
import { mainreducer } from "./Reducers";

export const Store = createStore(mainreducer);

We have to make use of Reducer functions to change the state in the store. So when we create a store we have to pass the Reducer to it.

Reducers

Reducer is a function that takes the current instance of the store and returns the updated version of the store.

Reducers are responsible for state change in Store

Reducer function needs two things as an argument

  • Copy of current state ( initial state )

  • Action ( It indicates something need to be changed )

     import { ADDTOFAV, DELETEFAV } from "./ActionType";

//creating aIntial State
const INTIALSTATE = {
  Cart: [],
};

export const mainreducer = (state = INTIALSTATE, action) => {
  console.log(state.Cart);
  switch (action.type) {
    case ADDTOFAV:
      return {
        ...state,
        Cart: state.Cart.concat({
          title: action.title,
          img: action.img,
          id: action.id,
        }),
      };

    case DELETEFAV: 
      return {
        ...state,
        Cart: state.Cart.filter((item) => item.id != action.id),
      };

    default:
      return state;
  }
};

We always return new objects as Reducer needs immutable data.

There can only be only one Reducer in Redux known as a Root Reducer, but you can create a Reducer for every single piece of state and then combine it with a Root Reducer using the Combine reducer function.

Action

Actions will tell the store that the change is needed/required.

Actions carry the information to the store. According to the Redux docs, Actions are the only source of information.

Actions carry a Payload of information from your application to the reducer and then from the reducer to the store.

We pass the action to the Reducers and according to the action. type the responsible reducer will be invoked if we have multiple reducers. Action creators will also carry some data that will be used to modify the state using the reducer.

 export const addtofav = (title, img, id) => ({
  type: ADDTOFAV,
  title: title,
  img: img,
  id: id,
});

export const deletefav = (id) => ({
  type: DELETEFAV,
  id: id,
});

Actions are triggered or we can say dispatch from the UI by users. Suppose we have an add to cart functionality then, when the user clicks on the Add to cart button it will dispatch the add to cart action which will then carry the product title, id, img to the reducer via an action payload.

Cycle of Redux

To summarize let's see how the cycle of redux works in application.

Redux cycle.png

In the above figure, you can see the flow of redux.

UI trigger some actions and action carries some Payload. Payload is just a piece of the necessary information that will be passed to Reducer. The reducer takes the initial state and the payload to make the change in the Store. As the store gets updated i.e state changes UI component will re-render and we can see the updated UI.