이렇게 각기 다른 상태를 동시에 업데이트하는 상황에는 useReducer로 구현하는 것을 고민해보면 좋습니다. 이 Hook을 사용해보기 전에 간단한 예시를 확인해보겠습니다.

    카운터를 useReducer로 구현한다면 다음과 같이 구현할 수 있습니다.

    const initialState = {value: 1};
    
    function reducer(state, action) {
      switch (action.type) {
        case 'increase':
          return {value: state.value + 1};
        case 'decrease':
          return {value: state.value - 1};
        default:
          throw new Error('Unhandled action type');
      }
    }
    
    function Counter() {
      const [state, dispatch] = useReducer(reducer, initialState);
      const onIncrease = () => dispatch({type: 'increase'});
      const onDecrease = () => dispatch({type: 'decrease'});
    
      return (...)
    }

    이 코드를 보고 ‘왜 이 상황에 useState를 사용하지 않고 이렇게 복잡하게 구현하지?’라고 생각할 수 있습니다. 이렇게 간단히 업데이트하는 상황이라면 useState를 사용하는 것이 더 적합합니다.

    신간 소식 구독하기
    뉴스레터에 가입하시고 이메일로 신간 소식을 받아 보세요.