Re(act State Pro)ducer => Reducer
다시말해, 리듀서라고 불리는 이유는 리듀서가 reduce()함수에서 사용하는 콜백함수이기때문에 리듀서라고 불립니다.
(state, action) => newState
의 형태로 reducer를 받고 dispatch 메서드와 짝의 형태로 현재 state를 반환합니다. const [state, dispatch] = useReducer(reducer, initialArg, init);
const initialState = {count: 0};
// (state, action) => newState 형태의 reducer를 정의한다.
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);
// dispatch로 action의 type을 보내 state를 업데이트한다.
return (
<>
Count: {state.count}
<button onClick={() => dispatch({type: 'decrement'})}>-</button>
<button onClick={() => dispatch({type: 'increment'})}>+</button>
</>
);
}