useState의 대체 함수로 컴포넌트 상태관리하는 값이 많고 복잡하다면 useReducer를 사용하여 읽히기 쉽게 바꿔준다.
const initialState = {count: 0};
function reducer(state, action) { //reducer 함수 작성
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);
const onDecrease = () => {
dispatch({type: 'decrement'})
};
const onIncrement = () => {
dispatch({type: 'increment'})
};
return (
<>
Count: {state.count}
<button onClick={onDecrease}>-</button>
<button onClick={onIncrement}>+</button>
</>
);
}
const [state, dispatch] = useReducer(reducer, initialState);
state: 상태
dispatch: 함수
useReducer(리듀서함수, state의 초기값)