第一句話很重要增炭。
An alternative to useState.
表明底層還是useState實現(xiàn),且作為additional的hook我們其實不用他也可以實現(xiàn),那什么場景會需要useReducer呢?
如果你熟悉redux的話你會發(fā)現(xiàn)useReducer跟redux很像,上手很容易十酣。
const [state, dispatch] = useReducer(reducer, initialArg, init);</pre>
三個參數(shù)
reducer function reducer是一個利用action提供的信息,將state從A轉(zhuǎn)換到B的一個純函數(shù)
initialArg 初始化的state际长。返回值為最新的state和dispatch函數(shù)(用來觸發(fā)reducer函數(shù)耸采,計算對應(yīng)的state)
init function 非必須 我們在Lazy initialization的時候需要用到。至于什么場景什么情況會用到我們先看官方demo, 我們將官網(wǎng)demo放進codesandbox我們可以直接看出來
It lets you extract the logic for calculating the initial state outside the reducer. This is also handy for resetting the state later in response to an action
當(dāng)我們需要在reducer外部計算init state的時候我們可以把這部分邏輯提取出來工育,這也非常方便當(dāng)你需要在action中重置state
useReducer Concept
可以把UseReducer想象成一個后端虾宇,后端通常需要一個數(shù)據(jù)庫和一些APl來修改你數(shù)據(jù)庫的數(shù)據(jù)。
state 就是數(shù)據(jù)庫存儲你的數(shù)據(jù)
dispatch相當(dāng)于調(diào)用 API 端點來修改數(shù)據(jù)庫如绸。
你可以指定type表明哪一個API被調(diào)用.
你可以提供額外的數(shù)據(jù)在payload的屬性里, 這就像POST請求的body.
type 和 payload 都是提供給reducer的對象的屬性. 該對象被稱作action.
reducer 是 API 的邏輯嘱朽。 它在后端收到 API 調(diào)用(dispatch)時調(diào)用,并根據(jù)端點和請求內(nèi)容(action)處理如何更新數(shù)據(jù)庫.
Why useReducer
先上圖
再看看官網(wǎng)解釋
useReducer is usually preferable to useState when you have complex state logic that involves multiple sub-values or when the next state depends on the previous one. useReducer also lets you optimize performance for components that trigger deep updates because you can passdispatchdown instead of callbacks.
復(fù)雜的state邏輯
下個一個state依賴上一個state
需要提升performance
多個state相互依賴 (form表單)
userReducer VS useState
- init
const [state, setState] = useState(initialValue); // setState for useState
const [state, dispatch] = useReducer(reducer, initialValue); // dispatch for useReducer</pre>
- change state
// with `useState`
<button onClick={() => setCount(prevCount => prevCount + 1)}>
+
</button>
// with `useReducer`
<button onClick={() => dispatch({type: 'increment', payload: 1})}>
+
</button></pre>
Full Demo
我們創(chuàng)建了一個在表單情況下使用useReducer的情況
詳情參照代碼里的注釋
- JS
- TS
https://codesandbox.io/s/react-userreducer-form-ts-4ko55u
Preference
https://devtrium.com/posts/how-to-use-react-usereducer-hook#usereducer-a-backend-mental-model