React Tutorials

React Build Counter using useReducer Hook Tutorial

React js counter using the useReducer hook example. In this post, we will learn how to create a simple counter component using the advanced React useReducer hook.

We won’t be using any third-party plugin to build the counter feature in React. Instead, we will build this tiny functionality using a simple React hook.

The primary goal of this comprehensive tutorial is to make you more comfortable with the useReducer hook and the switch statement in React js.

Let us understand the useReducer hook and why it should be used in React js development.

To handle the simple states in React, we heavily rely on the useState hook. The useState hook helps a lot in managing linear states.

However, seldom we get to deal with more complex state logic, where the multiple sub-values or next state depends on the previous state or might be deep updates are required to handle the state in React.

That’s where the useReducer comes into play. This tutorial will teach you how to create use reducer hook to build a simple counter. A counter has a similar scenario of managing a complex state, and it poses the increment, decrement or current state.

We will show you how to use the useReducer hook to optimize the performance of the react counter component that involves triggering the deep update using the dispatch function.

How to Create Simple Counter in React using useReducer Hook and Switch Statement?

  • Step 1: Build React App
  • Step 2: Make Counter Component File
  • Step 3: Install Bootstrap Package
  • Step 4: Build Counter with useReducer Hook
  • Step 5: Update App.js File
  • Step 6: Run React Application

Build React App

To create the react, type the following command on the terminal then run the command.

npx create-react-app react-counter-app

Enter into the project’s root.

cd react-counter-app

Make Counter Component File

Head over to /components directory, inside this folder make sure to make the /ReactCounter.js file.

Then copy the following code and paste into the file.

import React from 'react'

export default function ReactCounter() {
  return (
    <div>React Counter</div>
  )
}

Add Bootstrap Module

Bootstrap is not mandatory however this powerful CSS framework speed up the ui creation process.

Type the command on command prompt and execute command to install the module.

npm i bootstrap

Build Counter with useReducer Hook

Get inside the ReactCounter.js file, in this file we will add the logic to create the counter feature.

You have to add the code inside the react counter component file.

import React from 'react'

const startingState = { count: 0 }

const reducerCounter = (state, action) => {
  switch (action.type) {
    case 'increment':
      return { count: state.count + 1 }
    case 'decrement':
      return { count: state.count !== 0 ? state.count - 1 : (state.count = 0) }
    default:
      throw new Error('Error occured in counter')
  }
}

export default function ReactCounter() {
  const [state, dispatch] = React.useReducer(reducerCounter, startingState)
  return (
    <div>
      <h2 className="mb-4">React useReducer Counter Example</h2>
      <div>
        <h2>{state.count}</h2>
        <button
          type="button"
          className="btn btn-primary"
          onClick={() => {
            dispatch({ type: 'decrement' })
          }}
        >
          decrement
        </button>
        <button
          type="button"
          className="btn btn-danger ms-2"
          onClick={() => {
            dispatch({ type: 'increment' })
          }}
        >
          increment
        </button>
      </div>
    </div>
  )
}

Update App.js File

In this step, we will be adding the ReactCounter component inside the App.js file. This process will invoke the useReducer counter in React app when loaded on the browser.

import React from 'react'
import ReactCounter from './components/ReactCounter'
import '../node_modules/bootstrap/dist/css/bootstrap.min.css'

function App() {
  return (
    <div className="container mt-3">
      <ReactCounter />
    </div>
  )
}

export default App

Run React Application

To run the react application on the browser you need to evoke the following command from the terminal.

npm start

You can view the app on the given url:

http://localhost:3000

Conclusion

Throughout this quick guide, we have tried to elaborate on how to build a simple React counter app.

To build such functionality, we covered various concepts of React; we started with setting up a new react app and created a simple counter component using the useReducer hook.

We learned how to invoke deep state in React, how to manage state via useReducer and most importantly, how to use switch statement in React to create the counter app.

Digamber

I am Digamber, a full-stack developer and fitness aficionado. I created this site to bestow my coding experience with newbie programmers. I love to write on JavaScript, ECMAScript, React, Angular, Vue, Laravel.

Recent Posts

React Redux Handle API Calls with Thunk Middleware Tutorial

In this post, we will learn how to work with HTTP requests in the Redux…

1 day ago

Node AJAX Retrieve Records from MySQL Database Tutorial

MySQL is a relational database management system based on SQL – Structured Query Language, and…

4 days ago

React Manage REST API State Globally with Context API Tutorial

React Js Handle Rest API data globally with Context and useState hook tutorial. In this…

1 week ago

How to Delete Data from MySQL Database using Node Js

Node js delete data from MySQL database tutorial; Throughout this guide, you will ascertain how…

1 week ago

Node Import CSV File Data to MySQL Database with HTML Form

In this tutorial, you will discover how to import CSV file into MySQL database using…

2 weeks ago

How to Handle Global State in React js using Context API

React Js Global state management with createContext hook example; In this tutorial, we will help…

2 weeks ago