You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: src/content/learn/extracting-state-logic-into-a-reducer.md
+14-6Lines changed: 14 additions & 6 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -2439,7 +2439,7 @@ textarea {
2439
2439
2440
2440
<Solution>
2441
2441
2442
-
Dispatching an action calls a reducer with the current state and the action, and stores the result as the next state. This is what it looks like in code:
2442
+
To implement this Hook, define a `dispatch` function. It receives an action and tells React how to calculate the next state from the previous state. This is what it looks like in code:
2443
2443
2444
2444
<Sandpack>
2445
2445
@@ -2527,8 +2527,7 @@ export function useReducer(reducer, initialState) {
Though it doesn't matter in most cases, a slightly more accurate implementation looks like this:
2616
+
Because the reducer calculates new state from previous state, pass an updater function to `setState` whenever possible. React will call it with the previous state. Naming its parameter `prevState` makes this clear:
This is because the dispatched actions are queued until the next render, [similar to the updater functions.](/learn/queueing-a-series-of-state-updates)
2624
+
You might instead calculate the next state directly from `state`:
2625
+
2626
+
```js
2627
+
functiondispatch(action) {
2628
+
constnextState=reducer(state, action);
2629
+
setState(nextState);
2630
+
}
2631
+
```
2632
+
2633
+
This works if you dispatch only one action before React renders again. However, React can batch multiple updates. In that case, every call to `dispatch` reads the same `state` value from the current render, so later actions can overwrite the result of earlier ones. Passing an updater function lets React apply each queued action to the state produced by the previous action, [similar to updater functions.](/learn/queueing-a-series-of-state-updates)
0 commit comments