×

React Redux

How to Use Redux with React Hooks

It is an open-source library of JavaScript which is used for managing the application state. React uses the Redux to build the user interface. It was first coined by Dan Abramov and Andrew Clark in 2015.

React redux allows the react components to read the data from the redux store, and it also dispatches the actions to the store to update the data. Redux helps the applications to scale by giving them a sensible way to manage the state through a unidirectional data flow model.

The unnecessary complexities from the Flux architecture have omitted in the redux. Redux does not have any dispatcher concept. Redux includes a single store, but flux includes several stores.

Why React Redux required?

The reasons that show the importance of redux are as follows:

  • It kept up-to-date on any API change to ensure that the react components are behaving as expected.
  • It internally implements many performance optimizations, which allow the components to re-render only when it needs actually.

Redux Architecture

Redux Architecture

The components of the redux architecture are as follows:

STORE: It is a place where the entire state of your application has listed. It is used to manage the status of the application and has a dispatch (action) function.

ACTION: It is sent or dispatched from the view, which is the payloads, and can be read by the reducers. It is an object which is created to store information about the user's event. It includes information like the type of action, time, and location of occurrence, its coordinates, and which state it has to change.

REDUCER: It reads the payloads from the actions and also updates the store by the state. It is a function that returns a new state from the initial state.

Get started with Redux

Installation React Redux

Requirement: It requires the React 16.8.3 or its later version.

For using the React redux with the React application, you have to run the following command:

npm install redux react-redux –save

Installation React Redux

React Redux Example

Here, we are showing two examples in which the first example is before using redux, and the second example is after using redux.

React Redux Example

Before using Redux

App.js

import React, { Component } from 'react';
import './App.css';

class App extends Component {
  state = {
    marks: 89,
  };

  onIncrease = () => {
    this.setState((prevState) => ({
      ...prevState,
      marks: prevState.marks + 1,
    }));
  };

  onDecrease = () => {
    this.setState((prevState) => ({
      ...prevState,
      marks: prevState.marks - 1,
    }));
  };

  render() {
    return (
      <div className="App">
        <h2>Marks: {this.state.marks}</h2>
        <button onClick={this.onIncrease}>Increase Marks</button>
        <button onClick={this.onDecrease}>Decrease Marks</button>
      </div>
    );
  }
}

export default App;

Output:

Before using Redux

On click Increasing marks button, you will get:

On click Increasing marks button

Similarly, on click the decreasing marks button, you will get:

decreasing marks button

After using Redux

Let us first understand some terms that are commonly used in the redux application.

Reducer: The reducer is nothing but a function that takes two parameters that are ‘Action’ and ‘State’ to calculate and return the updated state. It reads the payloads from the Actions and updates the store by using the state.

Components:  It concerned with how things will look, such as markup, styles. It is responsible for receiving the data and invokes the callbacks exclusively by using props. It does not matter from where the data is coming and how to change the data. It only renders what is providing to them.

Containers: It is a component that concerns how things work, such as fetching the data and updating the state. It gives behavior and data to other container components. It generally uses the redux state to read the data and dispatches the redux action for updating the data.

Store:  All of the container components requires access to the Redux store to subscribe to it. For this, you need to pass the store as a prop to every component. However, it gets uninteresting. So, it is recommended to use a special react-redux component, which makes the store available for all of the container components without passing it explicitly. It used once when the root component gets rendered.

Actions: It uses the ‘type’ property for informing about the data which should be sent to the store.

Now, let’s move towards the example using react-redux.

First, create the Store folder in the src folder of your react application. Then, create a reducer.js file within the Store folder.

Now, open your Index.js file and import some packages into it. It is the root file that is responsible for creating the store and rendering our react app component.

Let us try to understand the simplest example of the React-Redux application.

Index.js

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import {createStore} from 'redux';
import {Provider} from 'react-redux';
import reducer from './Store/reducer'; 
const store = createStore(reducer); 
ReactDOM.render(, document.getElementById('root'));
serviceWorker.unregister(); 

Now, open your App.js file.

App.js

import React, { Component } from 'react';
import './App.css';
import { connect } from 'react-redux';

class App extends Component {
  render() {
    return (
      <div>
        <p>Marks: {this.props.marks}</p>
        <button onClick={this.props.onIncrease}>Increase Marks</button>
        <button onClick={this.props.onDecrease}>Decrease Marks</button>
      </div>
    );
  }
}

const mapStateToProps = (state) => {
  return {
    marks: state.marks,
  };
};

const mapDispatchToProps = (dispatch) => {
  return {
    onIncrease: () => dispatch({ type: 'INCREASE_MARKS' }),
    onDecrease: () => dispatch({ type: 'DECREASE_MARKS' }),
  };
};

export default connect(mapStateToProps, mapDispatchToProps)(App);

./Store/reducer.js

const initialState = {
  marks: 89,
};

const reducer = (state = initialState, action) => {
  const newState = { ...state };

  if (action.type === "INCREASE_MARKS") {
    newState.marks++;
  }

  if (action.type === "DECREASE_MARKS") {
    newState.marks--;
  }

  return newState;
};

export default reducer;

Output:

After the successful execution of code, the output will be:

After the successful execution of code

On clicking the increasing marks button, the output will be:

On clicking the increasing marks button

On clicking the decreasing marks button, the output will be:

On clicking the decreasing marks button,

Related Topics

Difference Between State and Props in React

Comparison between State and Props State The state is an updatable structure which is used for containing data or information about the component. The state in a component can be changed over...

2 minutes read.

Pros and Cons of ReactJS

Pros and Cons of ReactJS There are various advantages, and disadvantages of ReactJS are as follows: Benefits of ReactJS 1. Easy to Learn and Use: ReactJS is very easy to use and learn. It has a good...

3 minutes read.

Comparison between React and Vue

Comparison between React and Vue React, and Vue both are the two most famous libraries of JavaScript that are used for creating thousands of websites today. The React and Vue both...

3 minutes read.

React JSX

React JSX As we know, all of the React components include a render function. The Render function specifies the HTML output of a React component. JSX is an acronym of JavaScript extension that...

3 minutes read.

React Native vs ReactJS

Difference between React Native and ReactJS React Native React Native is also an open-source JavaScript framework that is used for the development of a mobile application for iOS Android and Windows. It...

6 minutes read.

React Components

React Components Former, the developers used to write more than thousands of lines of code to develop a single-page application. These applications follow the structure of traditional DOM, and it was very challenging to make...

2 minutes read.

React Table

React Table The table represents an arrangement that organizes the information in the form of rows and columns. The table is mainly used for storing and displaying the data within a structured format. Features of...

2 minutes read.

React Constructors

What is constructor? The constructor is a method that is used for initializing the state of the object in the class. It calls automatically during the creation of an object in...

4 minutes read.

ReactJS Tutorial

ReactJS Introduction React Tutorial helps you to understand the basic and some advanced concepts of ReactJS. As of now, it is the essential front-end library that is developed by a...

3 minutes read.

React Router

What is React Router? Routing is a process by which a user can direct to different pages based on their actions and requests. ReactJS router is generally used to develop single...

10 minutes read.

React Component API

React Component API It is a top-level API. It provides reusability to the code in the application and makes it completely individual. It has several methods for: Creating Elements.Transforming Elements.Fragments. Now, we are explaining the three...

2 minutes read.

Features of ReactJS

ReactJS Features As of now, within the developers, ReactJS is gaining much popularity as the best JavaScript framework. It is crucial for the front-end ecosystem. There are some of the crucial features of ReactJS that are...

2 minutes read.

React Bootstrap

React Bootstrap React has a widely used JavaScript framework for creating web applications, and Bootstrap has become the most popular CSS framework. Single-page apps have become popular from the last few...

9 minutes read.

React Refs

React Refs The word ‘Refs’ is an abbreviation of ‘References’ in React. It is as similar as Keys in React. Refs are a function in React which is used for accessing the DOM element and...

7 minutes read.

Difference between Controlled and Uncontrolled component in ReactJs

Controlled Component In the controlled component, the input of the form element is handled by the component rather than the DOM. Controlled components have the functions that govern the data, which...

2 minutes read.

React Code Splitting

React Code Splitting React Code Splitting is the procedure of splitting the bundle files by which the files get easily loaded on the webpage. The react application bundles the files by using...

4 minutes read.

ReactJS vs AngularJS

Difference between ReactJS and AngularJS AngularJS AngularJS is the JavaScript framework that is open source, and it is also used to build a dynamic web application. It is developed in 2009 by...

5 minutes read.

React Portals

React Portals React portals were introduced by React 16.0 in September 2017. It gives you a way to render the element outside of the component hierarchy, i.e., within a separate component. Before React 16.0, it...

3 minutes read.

React Flux

React Flux Introduction It is an application architecture that is internally used by Facebook to build the client-web application with react. It is useful when the project includes dynamic data, and...

2 minutes read.

React Fragments

React Fragments The fragments in React are introduced from the 16.2 and above versions. Fragments allow you to group a list of child elements without adding any extra node in the DOM. In React,...

2 minutes read.