I do not understand how reducer knows that count is from state without using state's name in the code. I thought it was like "return {state.count: state.count + 1}". How does it work?
import { useReducer } from 'react';
const initialState = {count: 0};
const reducer = (state, action) =>{
switch(action.type){
case 'minus':
return {count: state.count + 1}
break;
case 'plus':
return {count: state.count - 1}
break;
case 'reset':
return initialState;
break;
}
return state;
}
const App = () =>{
const [state, dispatch] = useReducer(reducer, initialState);
return(
<div>
<button onClick={() => dispatch({type: 'menos'})}>-</button>
<div>{state.count}</div>
<button onClick={() => dispatch({type: 'mais'})}>+</button>
<button onClick={() => dispatch({type: 'reset'})}>reset</button>
</div>
);
}
export default App;
You have been declared reducer function and actions. Your dispatch look your actions type and change the state accordingly.you dont need to give states name only need to give actions type.