Skip to content

Commit 4827b16

Browse files
committed
add: useReducer example2
1 parent 7339757 commit 4827b16

File tree

1 file changed

+20
-3
lines changed

1 file changed

+20
-3
lines changed

ReactByPrasadSir/src/components/11_useReducer/examples/UseReducerEx2.jsx

+20-3
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,27 @@
1-
import React from 'react'
1+
import React, { useReducer } from 'react'
22

33
const UseReducerEx2 = () => {
4+
const initialState = 0
5+
let reducer = (state, action)=>{
6+
switch (action.type) {
7+
case 'add':
8+
return state + action.value;
9+
10+
case 'sub':
11+
return state - action.value;
12+
13+
default:
14+
return state;
15+
}
16+
17+
}
18+
const [state, dispatch] = useReducer(reducer, initialState);
19+
420
return (
521
<div>
6-
<h1 className='p-2 text-xl'>UseReducer Ex1</h1>
7-
{/* photo clicked */}
22+
<h1 className='p-2 text-xl'>UseReducer Ex2 using objects to pass values</h1>
23+
<button onClick={()=>{dispatch({type:'add', value: 10})}} className='p-2 rounded-md bg-orange-500 text-white'>Add: {state}</button>
24+
<button onClick={()=>{dispatch({type:'sub', value: 2})}} className='p-2 mx-2 rounded-md bg-orange-500 text-white'>Sub: {state}</button>
825
</div>
926
)
1027
}

0 commit comments

Comments
 (0)