-
Notifications
You must be signed in to change notification settings - Fork 0
/
UseReducer.js
42 lines (37 loc) · 885 Bytes
/
UseReducer.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/**
* useReducer
*
* Similar to setState, it's an Redux pattern to manage state
*/
function reducer(state, action) {
switch (action.type) {
case 'increment':
return state + 1
case 'decrement':
return state - 1
default:
throw new Error()
}
}
function App() {
const [state, dispatch] = useReducer(reducer, 0)
function decrement() {
// we could pass an paylod along
// dispatch({ type: 'decrement', payload: 2 })
dispatch({ type: 'decrement' })
}
function increment() {
dispatch({ type: 'increment' })
}
return (
<div>
<p>{state}</p>
<button onClick={decrement}>
decrement
</button>
<button onClick={increment}>
increment
</button>
</div>
)
}