Skip to content

Commit ac72597

Browse files
committed
Dispatch multiple actions
1 parent ceea6c0 commit ac72597

File tree

1 file changed

+31
-1
lines changed

1 file changed

+31
-1
lines changed

README.md

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6535,7 +6535,7 @@ Technically it is possible to write nested function components but it is not sug
65356535
65366536
281. ### Can you combine **useReducer** with **useContext**?
65376537
6538-
Yes, it's common to **combine** `**useReducer**` **with** `**useContext**` to build a lightweight state management system similar to Redux:
6538+
Yes, it's common to combine **useReducer** with **useContext** to build a lightweight state management system similar to Redux:
65396539
65406540
```js
65416541
const AppContext = React.createContext();
@@ -6550,6 +6550,36 @@ Technically it is possible to write nested function components but it is not sug
65506550
}
65516551
```
65526552
6553+
**[⬆ Back to Top](#table-of-contents)**
6554+
6555+
282. ### Can you dispatch multiple actions in a row with useReducer?
6556+
Yes, you can dispatch multiple actions in a row using `useReducer` but not directly in one call. You'd have to call dispatch multiple times or create a composite action in your reducer that performs multiple updates based on the action type.
6557+
6558+
**Example: Dispatching Multiple Actions**
6559+
You can define a custom function with dispatching actions one by one.
6560+
```js
6561+
function handleMultipleActions(dispatch) {
6562+
dispatch({ type: 'increment' });
6563+
dispatch({ type: 'increment' });
6564+
dispatch({ type: 'reset' });
6565+
}
6566+
```
6567+
After that, you need to invoke it through event handler
6568+
```js
6569+
<button onClick={() => handleMultipleActions(dispatch)}>
6570+
Run Multiple Actions
6571+
</button>
6572+
```
6573+
**Note:** You can also define a custom action type If you want multiple state changes to be handled in one reducer call.
6574+
```js
6575+
case 'increment_twice':
6576+
return { count: state.count + 2 };
6577+
```
6578+
Then dispatch
6579+
```js
6580+
dispatch({ type: 'increment_twice' });
6581+
```
6582+
65536583
**[⬆ Back to Top](#table-of-contents)**
65546584
## Old Q&A
65556585

0 commit comments

Comments
 (0)