Understanding useReducer in React

The useReducer hook is used for complex state manipulations and state transitions.

Mon Sep 20 2021

Understanding useReducer in React

Introduction

Hooks are the new features added in React 16.8. They let you manage the state without writing a class. There are various hooks provided by React. One of them is useReducer.

what is useReducer Hook?

The useReducer hook is used for complex state manipulations and state transitions. Rather than defining multiple states with useState we can easily manage states with useReducer.

Syntax

const [state, dispatch] = useReducer(reducer, initialArgs, init)

This syntax accepts the reducer function as its first parameter. Just like the useState, useReducer returns two values for which we use the array destructuring syntax. The first argument is the current value of the state and the second is the dispatch function. Inside the useReducer, we have the reducer function as its first argument. initialArgs is the initial argument and the init refers to initializing the state lazily. You can also simply just pass the reducer function and the initial state value.

How to use useReducer?

Step-1

First, create a react application. npx create-react-app projectName

Step-2

cd projectName

Step-3

we need to import the useReducer like this:

import { useReducer } from 'react'

Step-4

Now, inside the app function lets define useReducer

const [state, dispatch] = useReducer(reducer, initialState)

Here we are passing the reducer function and the initialState

Step-5

const initialState = {counter: 0}; Here we are setting the initial state. Setting the count value to zero.

Step-6

We will be implementing increment, decrement, and reset counter so in the reducer function we need to define all three like this:

function reducer(state, action) {
  switch (action.type) {
    case 'INCREMENT':
      return { counter: state.counter + 1 }
    case 'DECREMENT':
      return { counter: state.counter - 1 }
    case 'RESET':
      return { counter: 0 }
    default:
      throw new Error()
  }
}

This function takes the state and the type of action as parameters. Then we check the action type by applying a switch statement covering all three and the default cases. See how we are referring to the count variable by state.count and returning value for each case.

Step-7

Now in the HTML part let’s just display the counter value with three buttons to update its value.

<div className="container mt-3">
  <h3>Hi, this is a useReducer demo</h3>
  <p>Counter value: {state.counter}</p>
  <button
    type="button"
    class="btn btn-primary mr-3 "
    onClick={() => dispatch({ type: 'INCREMENT' })}>
    Increment
  </button>

  <button
    type="button"
    class="btn btn-primary mr-3 "
    onClick={() => dispatch({ type: 'DECREMENT' })}>
    Decrement
  </button>

  <button
    type="button"
    class="btn btn-primary mr-3 "
    onClick={() => dispatch({ type: 'RESET' })}>
    Reset
  </button>
</div>

On each button click, we are dispatching an action (INCREMENT, DECREMENT, or RESET). This dispatched value is passed to the reducer function.

Step-8

Running the application using the npm start command.

React.useReducer

We can Use React.useReducer when;

  • Your application architecture is complex and big in size
  • When the logic to update state is super complex or you want to update state deep down in your component tree
  • The state value is either an object or an array
  • You need a more predictable, and maintainable state architecture of the application

Conclusion

The useReducer hook is a nice addition to the React library which allows for a simpler, predictable and organized way to update our component’s state and makes sharing data between components a bit easier.

This article originally appeared on lightrains.com

Leave a comment

To make a comment, please send an e-mail using the button below. Your e-mail address won't be shared and will be deleted from our records after the comment is published. If you don't want your real name to be credited alongside your comment, please specify the name you would like to use. If you would like your name to link to a specific URL, please share that as well. Thank you.

Comment via email
Arsha S
Arsha S

Software Engineer at Lightrains Tech

Tags Recent Blogs