×

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

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 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.

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.

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.

React Conditional Rendering

React Conditional Rendering In React, the working of the conditional rendering is similar to the condition works in JavaScript. We use JavaScript operators for creating elements that represent the current state, and then the React...

3 minutes read.

React State

React 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 time. The change...

3 minutes read.

React Keys

React Keys A key can be defined as a unique identifier. In React, it is used for identifying the items that have changed, deleted, and updated from the lists. React Keys are helpful...

3 minutes read.

React Animation

React Animation The animation is a procedure in which an image is manipulated to appear as a moving image. It is widely used to create an interactive web application. In React, we have to...

4 minutes read.

React Forms

React Forms Forms are the important part of any web application. It allows the interaction of the user with the app as well as the gathering of the information from the...

3 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.

Difference Between React Flux and MVC

React Flux vs MVC MVC MVC is an acronym of 'Model View Controller.' It is the architectural pattern that is used to develop the user interface. It has three different logical components: The...

2 minutes read.

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.

React CSS

What is React CSS React CSS is used to provide the style to the React applications. The style attribute adds dynamically-computed styles at render time, and it is one of the most used...

5 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.

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.

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 Higher-Order Components

React Higher-Order Components In short form, Higher-Order Components are represented as HOC. The Higher-order component is an advanced technique to use component logic. HOC is a function that takes the component and returns the new...

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.

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 Events

React Events An event is an action that triggers a response of the user action or system-generated event. As HTML, React can also perform actions based on user events. React has the...

2 minutes read.