React Build Counter with useReducer and Switch Statement Tutorial

In this React counter component example, we will help you learn how to use the useReducer hook in React js application to build a simple counter component.

Additionally, look at how to use the switch case statement in React and gracefully manage the complex states.

Imagine you have a list of values; you have to write a program that checks the equality against every possible case that belongs to a specific value present in the list.

It sounds confusing, well it is far more simpler than it sounds; we know an eloquent way that deals with a similar scenario in the programming realm.

The useReducer hook makes your life less cumbersome by providing the flexibility to manage a single state through multiple events.

We will use the useReducer, and switch case statement to build the counter in React.

Hence, we will set a counter with initial state zero and add increment and decrement buttons. This counter feature will have a single state being managed from a single state.

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

  • Step 1: Create React Project
  • Step 2: Add Bootstrap Module
  • Step 3: Create Component File
  • Step 4: Create Counter in React
  • Step 5: Register Component in App
  • Step 6: View in Browser

Create React Project

In the first step, type the suggested command and let the react app install on your system.

npx create-react-app react-draft

Move into the app folder.

cd react-draft

Add Bootstrap Module

Bootstrap library offers handy UI components that drastically reduces ui creation time, however it is totally upto you to use this module or not.

Execute the suggested command from the terminal.

npm install bootstrap

Create Component File

In this step, you have to create the /components folder, create the /Counter.js file, given is the basic skeleton of a functional component in react.

import React from 'react'

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

Create Counter in React

Open the Counter.js file and add the following code into the file.

import React from 'react'

const initialState = { count: 0 }

const counterReducer = (state, action) => {
  switch (action.type) {
    case 'increase':
      return { count: state.count + 1 }
    case 'decrease':
      return { count: state.count !== 0 ? state.count - 1 : (state.count = 0) }
    default:
      throw new Error('Error occured')
  }
}

export default function Counter() {
  const [state, dispatch] = React.useReducer(counterReducer, initialState)
  return (
    <div>
      <h2 className="mb-5">React Simple Counter with useReducer Example</h2>
      <div className="h-100 p-5 text-white bg-dark rounded-3">
        <h2>{state.count}</h2>
        <button
          type="button"
          className="btn btn-danger"
          onClick={() => {
            dispatch({ type: 'decrease' })
          }}
        >
          Decrease
        </button>
        <button
          type="button"
          className="btn btn-success ms-2"
          onClick={() => {
            dispatch({ type: 'increase' })
          }}
        >
          Increase
        </button>
      </div>
    </div>
  )
}

-> It is more advanced than useState, preferable to manage the more complex states.

-> If you have multiple states, multiple ways of changing it or dependencies to other states, or when the next state depends on the previous one.

-> It lets you optimize performance for components that trigger deep updates because you can pass dispatch down instead of callbacks.

-> It takes reducer function with state and action arguments. Where state refers to previous state, action updates the current state in relation to dispatch({type: ‘event’, payload: value}) method.

-> Type refers to the event, and payload refers to the additional data that you can set with the state soon to be updated.

Register Component in App

The App.js file is the main component of React, therefore we have to register the Counter component attribute inside the App function.

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

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

export default App

View in Browser

In this step, we will see how to run the app to view on the browser, type the command and hit enter.

npm start

This is how your counter will look like on browser, you can now increase or decrease the numerical value.

React Build Counter with useReducer and Switch Statement Tutorial

Conclusion

In this step-by-step tutorial, we have learned how to create a simple counter in React.

To build the counter in react functional component, we used the react useReducer hook. After using the useReducer hook successfully, we managed to form the increment/decrement counter in react js.

Apart from that, we have also looked at how to use switch statements in react js and manage the multiple events for updating the single state.