今天我们来学习一个比 useState 更“工程化”的 Hook:useReducer
。
你可能听说过它,但不太确定该不该用、该怎么用。这节课,我们就用一张流程图、一个 demo,彻底弄懂 useReducer 的用法、场景和原理。
👉 它是 React 提供的另一个管理组件状态的 Hook。
但和 useState
不一样,它并不直接“设值”,而是通过:
dispatch(action) → reducer(state, action) → 返回新 state
这种流程式的方式,来更新状态。
你可能会问:为啥不用 useState 就好了?
因为:
适合用 useState | 更适合用 useReducer |
---|---|
状态简单(比如一个布尔值) | 状态结构复杂(比如一个对象中多个字段) |
每次更新只影响一小部分状态 | 多个状态之间互相关联,需要统一逻辑处理 |
不需要维护“状态变化规则” | 希望所有状态变化逻辑集中在一个地方,便于维护 |
简而言之:复杂逻辑,选 useReducer,更清晰、统一、可控。
const [state, dispatch] = useReducer(reducer, initialState);
reducer
:纯函数,接收 state
和 action
,返回新 state
initialState
:状态初始值dispatch
:你用来“发指令”的函数📌 核心记住一句话:dispatch 发 action,不是直接改状态。
我们来看一个 reducer 函数示例👇
function reducer(state, action) {
switch (action.type) {
case 'increment':
return { ...state, count: state.count + 1 };
case 'decrement':
return { ...state, count: state.count - 1 };
case 'reset':
return { ...state, count: 0 };
default:
return state;
}
}
💡 特别强调两个原则:
action 是一个普通对象,例如:
{ type: 'increment' }
{ type: 'initialize', name: 'Alice' }
用 TypeScript,你可以这样写更清晰:
type Action =
| { type: 'initialize'; name: string }
| { type: 'increment' }
| { type: 'decrement' }
| { type: 'reset' }
👉 优势:自动类型推导,写错字段也能被发现。
1️⃣ 定义 State
和 Action
类型 2️⃣ 编写 reducer
函数 3️⃣ 使用 useReducer(reducer, initialState)
4️⃣ 在组件里调用 dispatch({ type: '...' })
发起更新 5️⃣ React 自动执行 reducer,更新 state,触发重渲染
可以理解为是一个迷你 Redux,但不需要引入额外库。
✅ 适合:
❌ 不适合: