How to Build an Application Using Reactjs and Redux?

0
2836
Reactjs and Redux

State management is always a challenging scenario for web-based applications. For small applications, the state can be managed by the framework itself. But, when the application scales-up or complexity increases, it become a nightmare to keep track of each and every state. 

React is also capable of managing component states, parent-child relationships, state changes, etc. So, what is the problem? The problem arises when the application is increasing in size and complexity.

Now, what is the solution?  The solution is to separate the state management activities from the main React application. States should be handled by some other component/framework/library. And, the React application will be integrated with that state management third party entity. Here, Redux is the third-party JavaScript library used for global state management.

In this article, we will integrate a simple React application with the Redux library. Meanwhile, if you are the one who wants to become a React developer then you can read this self-explanatory article “How to become a React developer“.

What is the state of an object?

The state of an object can be defined as the value it contains (actually, the value of the variables) at any particular point of time. So, when the value changes, the state of that object changes automatically. Now, managing this state is a complex task when the application increases in volume. And, if the state of an object is not managed carefully, the application will show erroneous output.

ReactJS – A front end library

ReactJS is an open-source JavaScript library for building front end (user interfaces). Please note, that ReactJS is not a framework like AngularJS. ReactJS has three major components for building UI. First one is the React code snippets and building blocks used for building the application. The second one is the JSX, used to manipulate DOM. And, the third one is the virtual DOM, which improves the performance of the application.

Read More: React Native vs Flutter: Which is Better?

What is Redux?

We have already described the state of an object in our earlier section. The concept of the ‘state’ is very important before we talk about Redux. Redux is a state management system for JS applications. Redux can work with any JS framework or library like AngularJS, ReactJS, etc. Redux helps to manage the state of an application as a loosely coupled system. Redux follows uni-directional flow like flux, but it is not similar to flux.

Why we need Redux?

By default, React has the capabilities to manage the state of an application. But, the problem arises when states need to pass through various layers and the application is a big one. React can manage states when the application is simple and small. But, it fails when the application is complex. Redux comes into the picture to manages states as an external library and single source of truth. It holds the state of an application as a single object. So, there is no replication or chances of mismatch. All applications need to interact with Redux store to get the state, update it and return back.

Components of Redux

Following are the components of Redux.

  • Actions – Action is a plain JavaScript object which pass information from your application to the Redux store. All actions must have a ‘type’ property to define the type of action to be performed.
  • Reducer – Reducer is a pure function. It takes the previous state and action and returns a new state.
  • Store – A Store is an object which brings action and reducer together. It holds the application state, allows access to the current state and lastly, allows the state to be updated and returned back.

Installation and environment set-up 

In this section, we will build a simple React application with Redux as a state management framework.

First, we will install the following components to make our environment ready for the application.

  • Install React

Type the following command to install React component and create app

npm install -g create-react-app

create-react-app samplereactredux
  • Install Redux

Type the following command to install Redux component

npm install redux
  • Install React-Redux

Type the following command to install React and Redux binding component

npm install react-redux
  • Install Redux-Logger

Type the following component to install Redux logger

npm install redux-logger

Now, we are ready with our environment.

Sample application 

In this section, we will create a simple React-Redux application for an e-commerce application. We will only consider buy and sell actions from the user interface.

Following are the components for the sample React-Redux application.

Listing 1: Root file creating store and rendering React components.

import React from 'react'
import { render } from 'react-dom'
import { Provider } from 'react-redux'
import { createStore } from 'redux';
import reducer from '../src/reducer/index'
import App from '../src/Samplereactredux'
import './index.css';

const store = createStore(reducer)

render(
   <Provider store = {store}>
      <Samplereactredux/>
   </Provider>, document.getElementById('root')
)

Following is the action component. This code will create actions based on user input. And, these actions will be passed to the reducer component. This component will be there as index.js under actions folder.

Listing 2: This is the action component

export function buy() {
   return {
      type: 'BUY'
   }
}
export function sell() {
   return {
      type: 'SELL'
   }
}
export function reset() {
   return { type: 'RESET' }
}

Following is the reducer component. It will actually interact with Redux and change the state of different components.

Listing 3: This is the reducer component

const reducer = (state = 'none', action) => {
   switch (action.type) {
      case 'BUY': return state.set('buy') 
      case 'SELL': return state.set('sell') 
      case 'RESET': return state.set('none') 
	  default: return state
   }
}
export default reducer;

Now, this is the view component. It has buy, sell and reset buttons to initiate a transaction.

Listing 4: This is the view component

import React, { Component } from 'react';
class TransactionState extends Component {
   render() {
      const {transstate,buy,sell,reset} = this.props;
      return (
         <div className = "App">
            <div>{transstate}</div>
            <div>
               <button onClick = {buy}>BUY</button>
            </div>
            <div>
               <button onClick = {sell}>SELL</button>
            </div>
            <button onClick = {reset}>RESET</button>
         </div>
      );
   }
}
export default TransactionState;

Following is one of the most important part. This component interacts with the Redux store and pass the states to React components. So, it is basically a bridge between Redux store and React components.

Listing 5: This is the component to pass Redux state to React components

import {connect} from 'react-redux'
import TransactionState from '../component/transstate'
import {buy, sell, reset} from '../actions';
const mapStateToProps = (state) => {
   return {
      transstate: state
   };
};
const mapDispatchToProps = (dispatch) => {
   return {
      buy: () => dispatch(buy()),
      sell: () => dispatch(sell()),
      reset: () => dispatch(reset())
   };
};
Export default connect(mapStateToProps, mapDispatchToProps)(TransactionState);

Following is the root component of React. It renders the React app.

Listing 6: This is the root component of React.

import React, { Component } from 'react';
import './ReactApp.css';
import TransactionState from '../src/container/appContainer';
class ReactApp extends Component {
   render() {
      return (
         <div className = "ReactApp">
            <header className = "ReactApp-header">
               <TransactionState/>
            </header>
         </div>
      );
   }
}
export default ReactApp;

This application will display the state as but, sell or reset when the respective buttons are clicked.

Read More: How to build an application using ReactJS and Node back end server API?

Conclusion

In this article, we have discussed the state management by Redux. Redux is a state management library which can work with various front-end technologies like Angular, React, etc. It is really helpful to manage states in an efficient way. We have also discussed various components of Redux and how it can communicate with React components. Hope this article will help you to understand Redux and its integration with React components.

Previous articleTop Emerging Programming Languages Which You Should Know!
Next articleWhat ‘Not’ to Do When Using AWS?

LEAVE A REPLY

Please enter your comment!
Please enter your name here