React.js / React Hooks

Handling Complex State with useReducer

In this tutorial, we will dive into the useReducer React Hook. You will learn how to manage complex state logic in an organized and predictable way with reducers.

Tutorial 4 of 5 5 resources in this section

Section overview

5 resources

Introduces React hooks for functional components to manage state and side effects.

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

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Age Calculator

Calculate age from date of birth.

Use tool

JWT Decoder

Decode and validate JSON Web Tokens (JWT).

Use tool

Case Converter

Convert text to uppercase, lowercase, sentence case, or title case.

Use tool

Lorem Ipsum Generator

Generate placeholder text for web design and mockups.

Use tool

Interest/EMI Calculator

Calculate interest and EMI for loans and investments.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help