Quick demo for React Reducer usage.
You do not use the React.useState() function anymore.
import React from 'react'
export function counterReducer(state,action) {
let newState = {...state};
if(action.type==='INCREMENT'){
newState.count = state.count+1;
}
if(action.type==='DECREMENT'){
newState.count = state.count-1;
}
if(action.type==='RESET'){
newState.count = 0;
}
return newState;
}
function App() {
const [state, dispatch]= React.useReducer(counterReducer,{count:0,tag:'test'});
return (
<div id="app">
<h1>The (Final?) Counter</h1>
<p id="actions">
<button onClick={()=>dispatch({type:'INCREMENT'})}>Increment</button>
<button onClick={()=>dispatch({type:'DECREMENT'})}>Decrement</button>
<button onClick={()=>dispatch({type:'RESET'})}>Reset</button>
</p>
<p id="counter">{state.count} ({state.tag})</p>
</div>
);
}
export default App;