useReducer 는 state 처럼 리액트의 상태를 관리하는 Hook
useState 를 여러번 사용해야할 경우 유용하게 대체할 수 있지만
꼭 필요한 것은 아니다
여러 상태를 동시에 업데이트하는 상황에 고민해보면 좋다
useReducer 는 상태를 업데이트하는 로직을 컴포넌트 바깥에 구현할 수 있다는 장점이 있다
dispatch 라는 함수 하나로 다양하게 업데이트할 수 있기 때문에
Context와 함께 사용하면 유용하다
const initialState = {value: 1};
function reducer(state, action) {
switch (action.type) {
case 'increase':
return {value: state.value + action.diff};
case 'decrease':
return {value: state.value - action.diff};
default:
throw new Error('Unhandled action type');
}
}
function Counter() {
const [state, dispatch] = useReducer(reducer, initialState);
const onIncrease = () => dispatch({type: 'increase', diff: 1});
const onDecrease = () => dispatch({type: 'decrease', diff: 1});
return (...)
}
단점은 오히려 코드나 로직이 복잡해질 수 있음