Skip to content

Instantly share code, notes, and snippets.

@vishalkakadiya
Last active January 29, 2024 04:01
Show Gist options
  • Save vishalkakadiya/7683ea51e4c300eb543b19696e55dfa3 to your computer and use it in GitHub Desktop.
Save vishalkakadiya/7683ea51e4c300eb543b19696e55dfa3 to your computer and use it in GitHub Desktop.
React Reducer with very Simple Example
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