Year End Sale: Get Upto 40% OFF on Live Training! Offer Ending in
D
H
M
S
Get Now
Getting Started With React Redux : Part1

Getting Started With React Redux : Part1

27 May 2024
Intermediate
7.15K Views
9 min read
Learn with an interactive course and practical hands-on labs

ReactJS Course

We know that nowadays JavaScript is trending like never before, the market for single-page applications (spa) is demanding a lot of changes in terms of performance, reusability, and many other features. When we work with a large-scale application, at a time the main aspect of the application is to manage app cache and state throughout the application, the cycle of updating to the models will be tough to manage.

Specifically, in react, we have worked with the state, and if you are not aware so you need to learn about the state first, and if you are aware of React then you may hear about state and stateful components. So let me tell you that Redux is the thing that will help us to remove direct DOM rendering and manage states in a single place.

Read More - React Interview Questions For Experienced

What is Redux

As per the official Redux docs, a state can be described into three different principles.

Single Source of Truth

The state is the main focus in Redux, I mean to say that in your whole application, there will be a single object tree that manages the state for all the pages of our React application. The changes are made into the application will be directly reflected in the state or you can say a single object tree of the state located in a separate location.

State is Read-only

The state is always read-only, which means we cannot directly write nor do modification in states, but we can maintain by using actions which the most comprehensive part of redux as well. By emitting the action, we can change the state value, and further, we can proceed with the state data.

However the fundamental building blocks of the Redux are a single store, actions, reducers, and a middleware, and we need to have a good knowledge of these components or basic building blocks to be proficient with the Redux and Redux toolkit.

Changes are made with pure functions

We know already that we can change state via action so for that we can write pure reducers. Reducers are the pure functions that can take different actions data and also contains previous state data and at last, it will return updated data. Please find the following simple example of a reducer.

Example

In this example, you can see that I have created different action types for the Authentication module.

const auth = (state = initialSettings, action) => {
 switch (action.type) {
 case SIGNIN_USER:
 return {
 ...state,
 signin: action.payload
 };
 case AUTH_USER:
 return {
 ...state,
 authenticated: true
 };
 case UNAUTH_USER:
 return {
 ...state,
 authenticated: false
 };
 case AUTH_ERROR:
 return {
 ...state,
 errorInfo: action.payload
 };
 case ACCOUNT_DETAILS:
 return {
 ...state,
 accountDetails: action.payload
 };
 case RESET_SUCCESS:
 return {
 ...state,
 resetSuccess: action.payload
 };
 default:
 return state;
 }
};

export default auth;

You can see into above example that, every time when any action will be triggered, at the same time it returns previous state data along with updated data and will return updated and fresh data related to authentication operations like Auth success, Auth error, Auth user, Unauth use and Account details.

Reducers always look for the action name and according to the action name, the respective action response can be set to the state values and it might be added, updated, or deleted from the existing set of values, after doing the updates, it can be subscribed by the components across the app.

Read More - React Roadmap For Beginners

How Redux Works.

How Redux Works

This is the simple diagram I have created to show the flow that how redux works actually, starting from the action to be a trigger to the end part where the store will have an updated state, and then again this cycle will be followed based on multiple operations. Do not worry about the flow for now because we are going to learn everything in detail late on in this article.

Redux core concepts

In this introductory part of the Redux tutorial, we will go through four different but very essential parts of Redux which are listed below.

  • Reducer

  • Actions

  • Store

Reducer

Reducer is a kind of pure function, and it returns a combination of previous state data and newly updated data, at last, it will return the updated state to the store. Reduced data will always depend on actions results and responses. In our React with Redux application, we can have different reducers based on the module, like we can have different reducers for the Auth module, Employee module, and Common function module. For example, we have a module for employee management, and for CRUD operation we have a sample module like this.

Example
function reducer(state, action) {
 switch (action.type) {
 case 'ADD':
 return { ...state, added: true }
 case 'DELETE':
 return { ...state, deleted: false }
 case 'UPDATE':
 return { ...state, ...action.data }
 default:
 return state;
 }
}

In this example, we have different action types like Add, Delete and Update, so based on the action dispatched, our state will be updated their values.

Actions

Whenever our store will be configured, our next step is to dig into Actions, do not confuse them with action, actions are the function that occurs in different operations like adding data, Updating data, Selecting data, and Deleting data using the API.

Example

Let me give you a simple example of the Reset password function which is going to reset the user’s password.

export function resetSuccess(message) {
 return {
 type: RESET_SUCCESS,
 payload: message
 };
}

In the above example, our action type is RESET_SUCCESS and we are going to send the message about the action which we have performed as payload to the reducer. One thing about action to keep in mind is that it always consists type key which is used to represent every action uniquely.

Store

Ahh, we left the discussion about Store, now it's show time because the value of the store in Redux is high because without redux there is no use of Reducers and Actions. In one sentence :

  • A store is an object which combined the Reducers and ActionsYes, it’s true; Store is a building block for Redux and is used to combine all the reducers and actions which are created into your application.

  • Because I told you before in this article that there will be a single combined store in your application, and the state of the whole application will be maintained inside the single store.

Example

For that, we can create a combined reducer, and then we will pass it to the store.

const reducers = combineReducers({
 settings: Settings,
 auth: Auth,
 createproposal: CreateProposal,
 dashboard: Dashboard,
 commonfunctions: CommonFunctions
});

export default reducers;

Here in the above code snippet, we have different reducers like auth, settings, dashboard, and common functions. So we are going to combine them all in a single piece and going to pass them to the store just like below lines of code.

import reducers from './reducers';
const store = createStore(reducers);

As you can see that I have imported our combined reducer, and created a store with the combined reducer.

Why do we need to use Redux?

React work on state, props, and lifecycle methods eventually, but for connected components, it is a tough job to pass props from the parent to child component or the chain of child components, and as a result, it creates the situation called "Props Drilling" and to resolve such issue, we need to have some feature that allows us to manage global object from where the data can be accessed to the various components into the application.

Yes, it’s an obvious question you may have that why I should learn and uses redux, what are the needs to learn react. When we are working with large-scale applications, sometimes it may happen that we are confused about how to manage everything in a proper manner with ease, same time react takes all responsibility to manage everything about your application changes and states. The main advantage is that :

Learn Redux (once) and use it everywhere = Angular, React, and Vue.js. We know that React is a JavaScript-based library and we don’t have any restrictions like Angular which is a Framework, and yes it's true that it is one of the famous libraries to work with.

Once the project gets complex, it may have tons of components, hence, managing all the components using props is not a suitable approach and here it comes the concept of Redux which resolves the purpose of global data management by creating a single state object.

Redux in itself is not dependent on any of the UI frameworks, we can use it with React, VueJs, Ember, and other technologies. but to keep in mind that it is only possible for UI frameworks to use Redux through a UI library from where it is being used and that ties Redux to our UI framework

Advantages of Redux

We have covered so many different things about Redux so far, let me list down a few primary advantages of Redux.

  • Single application state

  • Minimal code

  • Small functionality yet effective results

  • Hot reloading

  • Easy to learn, easy to write

  • Immutable data structure

And I want to add one more thing community support is growing like never before for React and Redux because more and more people are engaged with this library and they have started using React in their business applications. So these are the primary advantages that I have felt so far about redux, and there are many more when you try to work with redux.

Summary

In this introductory part of Redux, we have covered so many different aspects of Redux which are listed below for the recap.

  • Redux introduction

  • What is Redux

  • Core concepts of Redux

  • Why we should Redux

  • Advantages to using Redux

    Thus it depends on our project requirement to choose like when we can choose Redux with React, not every time we should use it, but I can say it has so many advantages over other libraries or frameworks, Carry on learning with Redux, Thanks for reading.

Take our React skill challenge to evaluate yourself!

In less than 5 minutes, with our skill challenge, you can identify your knowledge gaps and strengths in a given skill.

GET FREE CHALLENGE

Share Article
About Author
Manav Pandya (Technical Author and Front-end Engineer)

Manav is Blogger, Technical Author, Freelancer, and working as a front-end engineer since last 2 year with the different technologies like Angular 2+, Node.js, React, ExpressJs, In a free time he likes to learn and contribute technical content to the community to share and spread the knowledge.
Accept cookies & close this