How to use React Hook useReducer?

 React’s useReducer is a hook. useReducer is listed in additional hooks. useState is implemented with useReducer. That implies that useReducer is primitive but can be used to do everything you can do using useState. The concept of Reduces became popular with the rise of Redux. Reducers manage state in an application. Reducers receive current state and actions to produce a new state.The rules Reducer should follow are:

It should return an expected or same output with the given inputs. 

The function doesn’t produce any side effects.

Syntax: const [state, dispatch] = useReducer(reducer, initialArg, init);

Let see how to use the useReducer Hook.


Import useReducer Hook.

import React, { useReducer } from "react";


Setup the initial state.


const initialState = { react: false, graphQL: false, angular: false };


Our example is a component with three buttons.


const Courses = () => {

  const [state, dispatch] = useReducer(counterReducer, initialState);


  const handleReactPress = () => {

    dispatch({ type: "REACT" });

  };


  const handleGraphQLPress = () => {

    dispatch({ type: "GRAPHQL" });

  };


  const handleAngularPress = () => {

    dispatch({ type: "ANGULAR" });

  };


  return (

    <div className="box">

      <h2>Use Reducer Example Component</h2>

      <p>

        Learning{" "}

        {state.react

          ? "React"

          : state.graphQL

          ? "GraphQL"

          : state.angular

          ? "Angular"

          : "Not Started"}

      </p>

      <div>

        <button

          type="button"

          onClick={handleReactPress}

          className="button is-grey"

        >

          React

        </button>

        <button

          type="button"

          onClick={handleGraphQLPress}

          className="button is-dark"

        >

          GraphQL

        </button>

        <button

          type="button"

          onClick={handleAngularPress}

          className="button is-grey"

        >

          Angular

        </button>

      </div>

    </div>

  );

};


In our component if the user clicks on any button we will update the state and mark it as completed.

Define the reducer in our app as shown below.


const coursesReducer = (state, action) => {

  switch (action.type) {

    case "REACT":

      return { react: true };

    case "GRAPHQL":

      return { graphQL: true };

    case "ANGULAR":

      return { angular: true };


    default:

      throw new Error();

  }

};


The reducer will take the parameters state and action and update the state of our application based on the action.