Skip to content

useReducer Hook

Managing 复杂状态使用 reducers, 操作, and reducer 模式 in React.

你将学到

  • 当到 use useReducer 相反的 useState
  • reducer 函数 and 操作对象
  • Dispatching 操作 and dispatch 函数
  • 组合 useReducer 使用 useContext for 全局状态

概念讲解

What Is useReducer?

useReducer is an alternative to useState for managing complex state logic. It follows the reducer pattern from Redux: state transitions are described by a pure reducer function that takes the current state and an action object, and returns the new state. You dispatch actions to trigger state changes. This pattern centralizes all state logic in one testable function and makes state transitions explicit and predictable.

When to Use useReducer

Use useReducer when you have state with multiple sub-values that are related, when the next state depends on the previous one in complex ways, or when you want to make state transitions more predictable and testable. If you find yourself writing many useState calls that are tightly coupled, or if your state update logic is spread across many handlers, useReducer can bring clarity. For simple independent values, useState is simpler.

The Reducer Function

A reducer is a pure function: (状态, 操作) => newState. It typically uses a switch statement on 操作.类型 to determine which state transition to apply. Each case returns a new state object — never mutate the existing state. The action object carries a 类型 string and optionally a payload with data needed for the transition. Reducers must be pure: no side effects, no API calls, no random values.

Dispatch and useContext

The useReducer hook returns [状态, dispatch]. You call dispatch({ 类型: "INCREMENT" }) to trigger a state change. A powerful pattern is to combine useReducer with useContext: create a context that provides both the state and the dispatch function, so any component in the tree can read the state and dispatch actions without prop drilling. This is a lightweight alternative to Redux for medium-sized applications.

Action Type Conventions

A common convention is to use uppercase string constants for action types: "ADD_ITEM", "REMOVE_ITEM", "FETCH_SUCCESS". This makes them easy to grep for and distinguishes them from variables. In TypeScript, you can define a union type for actions to get exhaustive checking in the reducer's switch statement, ensuring every case is handled and the compiler catches missing cases.

示例代码

              import { useReducer } from "react";

// Reducer function — pure, returns new state based on action.
function cartReducer(state, action) {
  switch (action.type) {
    case "ADD_ITEM":
      return { ...state, items: [...state.items, action.item] };
    case "REMOVE_ITEM":
      return { items: state.items.filter(i => i.id !== action.id) };
    case "CLEAR":
      return { items: [] };
    default:
      return state;
  }
}

function ShoppingCart() {
  const [state, dispatch] = useReducer(cartReducer, { items: [] });

  const addItem = (item) => dispatch({ type: "ADD_ITEM", item });
  const removeItem = (id) => dispatch({ type: "REMOVE_ITEM", id });

  return (
    <div>
      <h2>Cart ({state.items.length} items)</h2>
      <button onClick={() => addItem({ id: Date.now(), name: "Product" })}>Add</button>
      <button onClick={() => dispatch({ type: "CLEAR" })}>Clear</button>
      <ul>
        {state.items.map(item => (
          <li key={item.id}>
            {item.name}
            <button onClick={() => removeItem(item.id)}>Remove</button>
          </li>
        ))}
      </ul>
    </div>
  );
}
            

reducer handles ADD_ITEM, REMOVE_ITEM, and CLEAR 操作. 每个返回新 状态对象. 组件 dispatch 操作相反的 calling setters directly.

动手试一试

  • JSON Formatter

    Reducer 状态 and 操作对象是 JSON — 格式到 inspect transitions.

  • Code Diff

    Compare reducer logic 当添加新 操作类型.

常见错误

错误写法

Mutating 状态内部 reducer 相反的 returning 新对象

正确做法

Reducers 必须是 pure. 总是返回新 状态对象: { ...状态, 项: [...状态.项, newItem] }. 从不推送到 existing 数组 or 修改状态 directly.

错误写法

Putting 边副作用如 API calls 内部 reducer

正确做法

Reducers 必须是 pure 函数使用否 边副作用. 做 API calls in 事件处理函数 or useEffect, 然后 dispatch 操作使用 result. reducer 仅更新状态.

练习 useReducer Hook

6 个练习

练习 useReducer Hook

查阅不认识的术语

新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。

查看术语表

动手做项目

通过引导式项目应用所学,含起始代码与解决方案。

查看项目

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误