DEV Community

Cover image for useReducer Hook in React
Vansh Sharma
Vansh Sharma

Posted on • Originally published at vanshsharma.hashnode.dev

useReducer Hook in React

Welcome back again!

This is the fifth blog in the React Hook series, where we're learning about different hooks used in React, and today's hook is the useReducer hook. Before we get started, I'd recommend reading the last blogs of this series React Hooks. Though this hook is entirely independent of we can read and learn it without any prior knowledge of hooks, it would be beneficial to have some basic understanding of the hooks.

What is useReducer Hook

To handle the complex state in our application, we use the useReducer hook. It is the same as the useState hook, but instead, it is used to handle the states where we have to keep track of the complex states which rely on the complex logic.

Syntax:

useReducer(reducerFn, initialState )

  • reducerFn is the function that contains the logic to handle the manipulation of our state.
  • initialState is the initial state value of our state. It is primarily objects while using the useReducer.

useReducer hooks return the two values:

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

  • the state is the value of the current state
  • dispatch is the method that will be used to call our reducerFn.

Understand useReducer by Example

In the following example, we will create a simple app that will display the user's Name and Account Number. We will be using useReducer for this.

Step 1 => Import the useReducer Hook

Import the useReducer hook and define it in the component.

import React, { useReducer } from "react";

const UseReducer = () => {
  const [userData, dispatchData] = useReducer(userReducer, {
    userName: "Please Login!",
    userAccount: null
  });
};
Enter fullscreen mode Exit fullscreen mode

Here userData will be our value of the state then, and the initial value of the state will be an object with properties userName and userAccount.
dispatchData will be the method to call the userReducer function, which we will define in the coming section.

Step 2 => Define userReducer function:

We can define the userReducer function outside our component since all the values will be passed using the dispatchData method.

// Reducer function

const userReducer = (state, action) => {
  if (action.type === "LOGIN") {
    return {
      userName: action.data.name,
      userAccount: action.data.account
    };
  }
  if (action.type === "LOGGED_OUT") {
    return {
      userName: "You are logged out!",
      userAccount: null
    };
  }
};

Enter fullscreen mode Exit fullscreen mode

The userReducer function will take two arguments state and action. state is the value of the state then, and action is used to check for what action which if condition to render, and this type will be passed by the dispatchData method that we will define in the coming section.

Step 3 => Add the UI for the Application

We will create the UI for the application that will show the userName and userAccount numbers along with two buttons. One of them is to handle the login function and will call the loginHandler function once clicked, and the other button will handle the logoutHandler function.
Here is how the code for the UI will look like:

return (
    <div className="component">
      <p>{userData.userName}</p>
      <p>{userData.userAccount}</p>
      <div className="btns">
        <button onClick={loginHandler}>Login</button>
        <button onClick={logoutHandler}>Logout</button>
      </div>
    </div>
  );

Enter fullscreen mode Exit fullscreen mode

Step 4 => Define the loginHandler and logoutHandler functions

loginHandler and logoutHandler functions will use the dispatchData method to pass the object with property type and user details. The type will have the value LOGIN and which we will use in our userReducer function to call the specific if statement according to the value of the type.

// Login Handler
  const loginHandler = () => {
    dispatchData({
      type: "LOGIN",
      data: {
        name: "Hello Vansh Sharma",
        account: "Your account number is: 123456"
      }
    });
  };

  // Logout Handler
  const logoutHandler = () => {
    dispatchData({
      type: "LOGOUT"
    });
  };

Enter fullscreen mode Exit fullscreen mode

Combining the above all code snippets in the following codesandbox we get the following application:

Check the UseReducer.js to understand more.

When to use useReducer

As you can see the, setting up useReducer is more lengthy than using the useState hook; therefore prefer using the useReducer only if the state of the component depends on the complex function or the state of the component is complicated, like an object with many properties.

That's all for this blog.  Continue reading this React hook series to learn more about React hooks. In the next blog, we'll look at the useCallback hook that can be used to memorize the function.
Feel free to leave your valuable feedback in the comments below.

To learn more about React, JavaScript, and Web development, follow me on :

Reference: W3Schools

Top comments (0)