After studied both useState and useReducer, I am confused by useReducer's code, so reducer takes two argument (state, action), is the state same as the initialState, if so why use two different names? Second, useReduer takes two arguments (reducer, initialState), and return dispatch and state objects. So does it means actions from reducer happen first and then we put that inside useReducer hook, which is like a container for all kinds of actions?
I mean once some actions it performed, the state changed. This is like useState hook, so reducer function is similar to setState, so the reasons we use useReducers is probably becasue it returns dispatch function, that can basically do so many actions? I mean it comes down to have many useState hooks VS. one single useReducer?
const initialState = {count: 0};
function reducer(state, action) {
switch (action.type) {
case 'increment':
return {count: state.count + 1};
case 'decrement':
return {count: state.count - 1};
default:
throw new Error();
}
}
function Counter() {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<>
Count: {state.count}
<button onClick={() => dispatch({type: 'decrement'})}>-</button>
<button onClick={() => dispatch({type: 'increment'})}>+</button>
</>
);
}