
看到 useReducer 你可能會疑惑,這跟前幾天講的 Redux 裡的 Reducer 有什麼毛線關係嗎?
的確!useReducer 的觀念跟用法都跟 Redux 很像,所以如果你已經會 Redux,那 useReducer 你也已經會了!
useReducer 是 React 的 hook,讓我們可以用 reducer、action、dispatch 來操作 state,在先前我們已經使用過 useState 來操作 state,useState 的底層其實就是用 useReducer 實踐的,而 useReducer 可以說是用來處理複雜邏輯的 state
useReducer
state、dispatch、reducer 與初始值import { useReducer } from "react";
const [state, dispatch] = useReducer(reducer, initialArg, init);
state:狀態dispatch:呼叫 action 的方法reducer:對 state 做操作initialArg:初始值init:初始化 state 的函式,非必要的參數以下是一個使用 useReducer 的範例
import { 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();
  }
}
export default function App() {
  const [state, dispatch] = useReducer(reducer, initialState);
  return (
    <div>
      <h1>Count: {state.count}</h1>
      <button onClick={() => dispatch({ type: "decrement" })}>
        decrement
      </button>
      <button onClick={() => dispatch({ type: "increment" })}>
        increment
      </button>
    </div>
  );
}
點擊 decrement 減少 count,點擊 increment 增加 count
打開 codesandbox 程式碼範例 看看
雖然 useReducer 跟 Redux 很像,但是無法完全取代 Redux,useReducer 無法存取 global store,必須搭配 context API 才能做出類似簡易版 Redux 的效果,適合在較輕量的專案
本文將同步更新至我的部落格
Lala 的前端大補帖