什麼是 useReducer?
useReducer 是 React 提供的一個 Hook,讓你用「發送指令」的方式來管理元件的狀態。
useReducer 概念
- reducer 函式:負責接收「目前狀態」和「動作指令」,然後回傳新的狀態。它就是廚房的大廚,根據訂單出菜。
- dispatch 函式:用來發送動作指令的工具,就像你按下點餐鈴,告訴系統「我要做某件事」。
- action 物件:一個描述「要做什麼」的物件,通常包含一個 type 屬性,例如
{ type: "加一" }。
useReducer 語法
- reducer:一個函式,接收 (state, action) 兩個參數,回傳新的 state。
- initialState:狀態的初始值,例如數字 0 或物件 {}。
- state:目前的狀態值,供畫面渲染使用。
- dispatch:呼叫它並傳入 action,就會觸發 reducer 計算新狀態。
import { useReducer } from "react";
// const [state, dispatch] = useReducer(reducer, initialState);
// 定義 reducer:根據 action 的 type 決定新狀態
function reducer(state, action) {
switch (action.type) {
case "加一": return { count: state.count + 1 }; // 回傳全新物件
case "歸零": return { count: 0 };
default: return state; // 未知指令就保持不變
}
}
export default function Counter() {
const [state, dispatch] = useReducer(reducer, { count: 0 }); // 初始值為 0
return (
<div>
<p>目前計數:{state.count}</p>
<button onClick={() => dispatch({ type: "加一" })}>+1</button> {/* 發送動作指令 */}
<button onClick={() => dispatch({ type: "歸零" })}>重設</button>
</div>
);
}
















