How to Use the React useReducer Hook



In this article, you will learn how to use the React useReducer hook.

Using the useReducer hook

React’s useReducer hook is a powerful tool for managing complex state logic in your application. It allows you to define a state management function and dispatch actions to update the state. Here’s how to use the useReducer hook:

Define your initial state

The first step in using useReducer is to define your initial state. This is the starting point for your state management function. It can be an object, an array, a string, or any other type of data that you need to keep track of.

const initialState = { count: 0 };

Define your reducer function

Next, you need to define your reducer function. This is a pure function that takes in the current state and an action, and returns the updated state. The reducer function should never mutate the original state object. Instead, it should return a new state object with the updated values.

function reducer(state, action) {
  switch (action.type) {
    case "increment":
      return { count: state.count + 1 };
    case "decrement":
      return { count: state.count - 1 };
      throw new Error();

Use the useReducer hook

Now that you have your initial state and reducer function, you can use the useReducer hook in your component. The hook takes two arguments: the reducer function and the initial state.

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

The useReducer hook returns an array with two values: the current state and the dispatch function. You can use the current state in your component to display data, and you can use the dispatch function to update the state.

Dispatch actions to update state

To update the state, you need to dispatch actions. An action is an object with a type property that describes the update you want to make to the state. You can also include additional data in the action object as needed.

function handleIncrement() {
  dispatch({ type: "increment" });

function handleDecrement() {
  dispatch({ type: "decrement" });

When you call the dispatch function with an action object, React will pass that action to your reducer function. Your reducer function will then update the state based on the action type, and return the new state object.

Use the updated state in your component

Finally, you can use the updated state in your component to display data. You can access the current state by using the state variable returned by the useReducer hook.

return (
    <p>Count: {state.count}</p>
    <button onClick={handleIncrement}>+</button>
    <button onClick={handleDecrement}>-</button>

In this example, we’re displaying the current count value from the state object. When the user clicks the “+” button, we call the handleIncrement function, which dispatches an “increment” action. This action updates the count value in the state object, which causes the component to re-render with the new value displayed.