前言:
主要就紀錄一下目前 React
官網筆記
參考資料:
Basic Logic
reducer logic is like Declarative and normal way is to change state is imperative way
What is Reducer ?
It mainly handle state logic and it receive two parameterscurrentState
、 action
object
1 | dispatch( |
Reduce function
1 | function reducerfunction(state, action){ |
Notes
React 中 reducer 概念其實跟 Javascript array 方法 reduce 很像。他們都是在拿目前的值跟目前的 action、 接著返回下一個值
useReducer Hooks
Will take two parameters
- reducer function
- initial state
Returns
- state value
- dispatch function
1 | const [state, dispatch] = useReducer(reducerFunction, initial state) |
Reducer writing Hint
- We should only use pure function
not mutate
any more - Each action describes a single user interaction
- useImmerReducer hooks if you need it
Pros
- 優點就是可以把 state 邏輯拆開共用,UI 畫面可以更單純處理事件行為
- 增加可讀性和除錯
Cons
- code 必須寫更多行
- 如果沒有 reduce 概念會看不懂