Understanding useReducer hook in React

Aswathy E G
2 min readOct 4, 2021

A brief overview of useReducer hook in React

Photo by Hans-Peter Gauster on Unsplash

Introduction

In this post, I would like to walk you through useReducer hook in React, which helps us to centralise all state modification in one place.

In my previous post, I explained state management with a simple example of counter, using class components and functional components. If you are unfamiliar with useState hook in React, please refer to the post here.

Here, I am going to explain the functionality of useReducer with the same counter example for simplicity purpose.

useReducer is an alternative to useState. It is useful for developers who are handling complex state logic in which the next state depends on the previous one.

The basic setup

I’m assuming that you already have a React project setup. If not, please refer here.

Now, let’s import useReducer from React. Then declare useReducer hook inside our function.

declaration

Here state is the default value of our component’s state. dispatch will let us dispatch actions that will trigger state changes.

You might be thinking “What is this actions?” Hold your thoughts. We’ll get it in a minute.

useReducer accepts two parameters: reducer and initialState. As it’s name suggests, initialState is the initial value of the state. Let’s analyze the reducer function a bit deeper.

Reducer function in useReducer

Here is the structure of reducer function.

reducer function

In simple words, reducer takes an initial state and give us a way to alter that state based on the rules we set. These rules are the actions here. In our example, the rules are increment and decrement.Conventionally, action is an object that has a type and payload. The type is like an id of this action and payload is a data that the action transfers (optional).

Let’s look at the full example to understand more.

complete example

In situations where you have to handle a group of state variables, declare the initialState as follows:

initialize state

In this post, I used a simple counter example to explain the functionality of useReducer. Once you are clear with the idea, you can use the same approach to update the state in complex situations as well .

Thanks for your time! Happy coding to all !

--

--