useReducer

Pranchal Agrahari
Last Updated: May 13, 2022

Introduction

With the introduction of hooks in react, a new way of writing and thinking about components has been introduced. One of the most popular hooks is useReducer which helps in the manipulation and handling of state of react components. We will be learning about useReducer in detail through this article.

In react, there are two hooks to handle the state of components, namely

1.useState

2.useReducer

You might be familiar with the useState hook in react, if not, then you can read out this blog for better understanding.

The useReducer is a better alternative to useState as it is easy to handle complex states in useReducer.

But before getting into details, let's see what useReducer is.

useReducer

useReducer is used to store and update the states. It is used for state manipulation and complex state transitions. Just like other hooks in react, it can be imported by the use of the following snippet.

import { useReducer } from "react";

 

The useReducer takes three arguments: reducer, initial state, and function to load the initial state.

Syntax:

Const [state, dispatch]= useReducer(reducer,initialState,init)

 

Let’s discuss each argument in the syntax in detail:

Reducer

This is a function that tells what the state should contain depending upon the action taken. It returns an object that is used to update the state. It takes two arguments which are state and action. The action is like an instruction you pass to the reducer function. Based on the action specified, the reducer function executes the necessary state update.

Initial State

The second argument passed  is initial State . It represents the default state of the component. Note that if you don’t pass the third argument to useReducer which for initializing the initial state, it will take the second argument as the initial state. The third argument is optional.

Creating the initial state lazily

Lazy initialization is a tactic used in programming to delay the creation of an object or a complex calculation until the first time it is needed.

We already know, useReducer can accept three parameters, but the third parameter is an optional parameter. init function for creating the initial state lazily is optional which lets you extract logic for calculating the initial state outside of the reducer function

The dispatch method

The dispatch function accepts an object representing the type of action we want to execute when called. It sends the kind of action to the reducer function to perform its job, which, of course, is updating the state.

Now we have discussed the useReducer in detail. Let's implement an application to understand it better.

Creating a counter using useReducer

We will create a counter app which will have three button addition ,subtraction and reset.

import React, { useReducer } from "react";
import ReactDOM from "react-dom";


const initialState = { count: 0 }
 // The reducer function
function reducer(state, action) {
  switch (action.type) {
    case 'add':
      return { count: state.count + 1 }
    case 'subtract':
      return { count: state.count - 1 }
    case 'reset':
      return {count: state.count = 0}
    default:
    return { count: state.count  }
  }
}

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

  return (
    <div>
      Count: {state.count}
      <br />
      <br/>
      <button onClick={() => dispatch({ type: 'add' })}>+</button>
      <button onClick={() => dispatch({ type: 'subtract'})}>-</button>
      <button onClick={() => dispatch({ type: 'reset'})}>Reset</button>
    </div>
  );
};


ReactDOM.render(<Counter />, document.getElementById('root'));

 

 

Output

First, we initialize the state with 0, and created  a reducer function which accepts the current state of count as an argument and an action. The state is updated by the reducer on the basis the action type. add, subtract, and reset are all action types that, when dispatched, update the state of our app accordingly.

useReducer Vs useState

One question that arises after reading all discussion above is if we have useReducer than what’s the use of useState or vice-versa.

The answer is straightforward. Both of them have been designed to co-exist and were never created to replace each other. But there are some scenarios in which we should use useState and situations in which we should use useReducers.

We should preferably use useReducer in the following case.

  1. Your application is complex and big in size.
  2. When logic to update the state is complex.
  3. The state value is either an array or object.
  4. To create a more maintainable and predictable state architecture of the application.


We should more preferably use useState in the following case.

  1. Application is small.
  2. The state has some primitive values.
  3. Simple state transitions
  4. Logic is not complicated and can be handled within one component.

Frequently Asked Questions

1.What is useReducer?

useReducer is used to store and update the states. It is used for state manipulation and complex state transitions

2.what is lazy initialization?

Lazy initialization is a tactic used in programming to delay the creation of an object or a complex calculation until the first time it is needed.

3.What is the syntax for useReducer?

The syntax for the use reducer is

Const [state, dispatch]= useReducer(reducer,initialState,init)

 

Key Takeaways

The blog discussed the useReducer in detail along with its syntax. We also implemented an example code to understand it better. We conclude our discussion with the case-specific use of useReducer and useState.

If you are preparing for the next interview, check out the blogs 15 Most Frequently Asked React JS Interview Questions and 10 Best ReactJS Interview Questions. And if you are a beginner, check out the Top 5 skills to learn before you start with ReactJs to know the prerequisites to learn React.

If you are preparing for your DSA interviews then, Codestudio is a one-stop destination. This platform will help you acquire effective coding techniques and give you an overview of student interview experience in various product-based companies

Was this article helpful ?
0 upvotes

Comments

No comments yet

Be the first to share what you think