Handling Complex State with useReducer

Tutorial 4 of 5

Introduction

In this tutorial, we're going to learn how to manage complex state logic in a React application using the useReducer hook. By the end of this tutorial, you'll be able to:

  • Understand what a reducer is and how to use it.
  • Understand how to use the useReducer hook in React.
  • Apply useReducer to manage complex state logic in a React application.

Prerequisites:

  • Basic knowledge of JavaScript.
  • Basic understanding of React.

Step-by-Step Guide

Understanding Reducers

A reducer is a function that takes the current state and an action, and then returns a new state. It’s called a reducer because it’s the type of function you would pass to JavaScript’s Array.prototype.reduce(reducer, ?initialValue) method.

Understanding useReducer

The useReducer is a hook in React that is used for state management. It is an alternative to useState. What useReducer does is it accepts a reducer of type (state, action) => newState, and returns the current state paired with a dispatch method.

Example:

import React, { useReducer } from 'react';

const initialState = {count: 0};

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

function Counter() {
  const [state, dispatch] = useReducer(reducer, initialState);
  return (
    <>
      Count: {state.count}
      <button onClick={() => dispatch({type: 'increment'})}>+</button>
      <button onClick={() => dispatch({type: 'decrement'})}>-</button>
    </>
  );
}

export default Counter;

In this example, we're using useReducer to manage the state of a simple counter. When the '+' button is clicked, we dispatch an action of type 'increment', which causes the reducer to increase the count by 1. Similarly, clicking the '-' button dispatches a 'decrement' action, which decreases the count by 1.

Code Examples

Example 1: Managing Multiple State Variables

import React, { useReducer } from 'react';

const initialState = {
  firstName: '',
  lastName: '',
  email: '',
};

function reducer(state, action) {
  return {
    ...state,
    [action.name]: action.value,
  };
}

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

  const handleChange = (event) => {
    dispatch(event.target);
  };

  return (
    <form>
      <input name="firstName" value={state.firstName} onChange={handleChange} />
      <input name="lastName" value={state.lastName} onChange={handleChange} />
      <input name="email" value={state.email} onChange={handleChange} />
    </form>
  );
}

export default MyForm;

In this example, we're using useReducer to manage the state of a form with multiple input fields. Each time the user types into an input field, the handleChange function dispatches an action containing the input's name and current value. The reducer then updates the appropriate field in the state.

Summary

In this tutorial, we learned about reducers and how to use the useReducer hook in React to manage complex state logic. We saw how useReducer can be used to manage multiple state variables and handle complex state transitions.

Practice Exercises

  1. Create a to-do list application using useReducer. The app should allow the user to add new to-dos, mark to-dos as completed, and delete to-dos.

  2. Create a shopping cart application using useReducer. The app should allow the user to add items to the cart, increase or decrease the quantity of an item in the cart, and remove items from the cart.

Additional Resources