Last active
January 29, 2024 04:01
-
-
Save vishalkakadiya/7683ea51e4c300eb543b19696e55dfa3 to your computer and use it in GitHub Desktop.
React Reducer with very Simple Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useReducer } from 'react'; | |
export function counterReducer(state, action) { | |
if (action.type === 'INCREMENT') { | |
return { | |
count: +state.count + 1 | |
}; | |
} | |
if (action.type === 'DECREMENT') { | |
return { | |
count: +state.count - 1 | |
}; | |
} | |
if (action.type === 'RESET') { | |
return { | |
count: 0 | |
}; | |
} | |
return state; | |
} | |
function App() { | |
const [counter, counterDispatch] = useReducer(counterReducer, { | |
count: 0 | |
}); | |
const handleIncrement = () => { | |
counterDispatch({ | |
type: 'INCREMENT' | |
}); | |
} | |
const handleDecrement = () => { | |
counterDispatch({ | |
type: 'DECREMENT' | |
}); | |
} | |
const handleReset = () => { | |
counterDispatch({ | |
type: 'RESET' | |
}); | |
} | |
return ( | |
<div id="app"> | |
<h1>The (Final?) Counter</h1> | |
<p id="actions"> | |
<button onClick={handleIncrement}>Increment</button> | |
<button onClick={handleDecrement}>Decrement</button> | |
<button onClick={handleReset}>Reset</button> | |
</p> | |
<p id="counter">{counter.count}</p> | |
</div> | |
); | |
} | |
export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment