What is useReducer hook in react


Posted 1 month ago by Ryan Dhungel

Category: React Hooks

Viewed 223 times

Estimated read time: 10 seconds

In this tutorial you will learn how to use useReducer hook in react.

  1. useReducer is an alternative to useState
  2. It takes a reducer as an argument
  3. Example of reducer using arrow function (state, action) => newState
  4. reducer function takes a state and action. Actions will make some changes to the state.
  5. Once actions do their job, reducer then returns a new state
  6. A reducer is a function that determines changes to an application's state paired with dispatch method
  7. It works similar to how redux works
  8. useReducer is usually preferable to useState when you have complex state logic that involves multiple sub-values or when the next state depends on the previous one

Here is an example of using useReducer in react app

import React, { useReducer } from "react";

// initial state
const initialState = { count: 0 };

// reducer function
const reducer = (state, action) => {
  switch (action.type) {
    case "INCREMENT":
      return { count: state.count + 1 };
    case "DECREMENT":
      return { count: state.count - 1 };
    case "RESET":
      return { count: 0 };
    default:
      throw new Error();
  }
};

const Counter = () => {
  // useReducer first argument is reducer function. second argument is initialState
  // you can destructure state value and dispatch function to access/modify state
  // dispatch function takes type/string and payload/data
  // IMPORTANT! pass the initial state as a second argument
  const [state, dispatch] = useReducer(reducer, initialState);
  return (
    <>
      Count: {state.count}
      <button onClick={() => dispatch({ type: "INCREMENT" })}>+</button>
      <button onClick={() => dispatch({ type: "DECREMENT" })}>-</button>
      <button onClick={() => dispatch({ type: "RESET", payload: 0 })}>
        RESET
      </button>
    </>
  );
};

export default Counter;