If we look at the standard example of increment, decrement with useReducer hook:
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>
</>
);
}
As I understand it, the useReducer function in the above code has bound 'dispatch' to the 'reducer' function so when we call dispatch it executes the reducer function. However, looking at the code the reducer function expects 2 params, however we only pass it one param when we execute dispatch - but it works. Why is this?.. many thanks.