React.js

useReducer Hook in React-js

Welcome readers, in this tutorial, we will understand how to use the useReducer hook in a react-js application.

1. Introduction

React is a flexible javascript library responsible for building reusable UI components. It is an open-source component-based frontend library responsible only for the view part of an application and works in a virtual document object model. But before that let us take a look at the differences between angular and react –

AngularReact
Complete frameworkLibrary
Object-oriented programmingExtension to the javascript library and its internal architecture is based on jsx
Based on the model view controller and real document object modelBased on the virtual document object model

1.1 useReducer hook in React-js

Hooks in react-js are the functions that are hooked into react-js state and lifecycle features from function components. The useReducer(…) hook is sometimes used to manage the state of an application. It is similar to the useState(…) hook just a bit more complex and acts as an alternative to manage the complex state in your application. It is a pure function that has no disadvantages. Any function in javascript is considered is pure when –

  • The function that always returns the same output if the same arguments are passed to the function
  • The function does not show any ill effects

The useReducer hook is represented by the below syntax in react-js –

Hook syntax

const [state, dispatch] = useReducer(reducerFunction, initialArgument);

1.2 Setting up dependencies

To play with React let us set up some of the required dependencies.

1.2.1 Setting up Node.js

To set up Node.js on windows you will need to download the installer from this link. Click on the installer (also include the NPM package manager) for your platform and run the installer to start with the Node.js setup wizard. Follow the wizard steps and click on Finish when it is done. If everything goes well you can navigate to the command prompt to verify if the installation was successful as shown in Fig. 1.

Fig. 1: Verifying node and npm installation
Fig. 1: Verifying node and npm installation

1.2.2 Setting up React-js project

Once the Nodejs setup is successful we will use the below command to install the React library and set up the project. Do note that the npx package is available with the npm 5.2 version and above.

Create project structure

$ npx create-react-app usereducer-app

The above command will take some time to install the React library and create a new project named – usereducer-app as shown below.

Fig. 2: usereducer Project structure
Fig. 2: usereducer Project structure

2. useReducer hook in React-js

To set up the application, we will need to navigate to a path where our project will reside and I will be using Visual Studio Code as my preferred IDE.

2.1 Setting up the React code

To understand a practical implementation let us go through some hands-on exercises.

2.1.1 Creating components

Create a folder named components in the src folder.

2.1.1.1 Creating usereducer component

Add the following code to the UseReducer.js file. The file will be responsible to handle the interactions with the reducer hook with the help of two buttons and show the counter value on the page.

UseReducer.js

import React, { useReducer } from "react";
import "./UseReducer.css";

const initialState = 0;

const reducer = (state, action) => {
  // console.log(state, action);
  if (action.type === "INC") state = state + 1;

  if (action.type === "DEC") state = state - 1;

  return state;
};

const UseReducer = () => {
  const [state, dispatch] = useReducer(reducer, initialState);

  return (
    <div>
      <p className="counter">Counter: {state}</p>
      <div>
        <button
          type="button"
          className="button"
          onClick={() => dispatch({ type: "INC" })}
        >
          Increment
        </button>
        <span> </span>
        <button
          type="button"
          className="button"
          onClick={() => dispatch({ type: "DEC" })}
        >
          Decrement
        </button>
      </div>
    </div>
  );
};

export default UseReducer;

2.1.2 Creating implementation file of usereducer App

In the App.js component we will include the use reducer component and specify the generic header information content for the application.

App.js

import "./App.css";
import UseReducer from "./components/UseReducer";

function App() {
  return (
    <div className="App">
      <h1>useReducer hook example in ReactJs</h1>
      <i>Click on buttons to play with the counter value</i>
      <UseReducer></UseReducer>
    </div>
  );
}

export default App;

3. Run the usereducer App

To run the application navigate to the project directory and enter the following command as shown below in the terminal.

Run command

$ npm run start

The application will be started on the default port. In case the application does not get started on the default port you can change the port number as per your requirement. I have changed the default port to 2000.

Fig. 3: usereducer Application run
Fig. 3: usereducer Application run

4. Demo

The application will be started in the default browser as shown below and a welcome page will be shown.

Fig. 4: Application home page
Fig. 4: Application home page

The application page shows 2 buttons that you can click to increase or decrease the counter. The counter value is handled with the help of the useReducer(…) hook. That is all for this tutorial and I hope the article served you with whatever you were looking for. Happy Learning and do not forget to share!

5. Summary

In this tutorial, we created a React application and understood the useReducer() hook in React-js. You can download the source code from the Downloads section.

6. Download the Project

This was a tutorial to understand the useReducer() hook in a React application.

Download
You can download the full source code of this example here: useReducer Hook in React-js

Yatin Batra

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button