UseReducer

코딩덕·2024년 4월 22일

💡 UseReducer

State Hooks에는 useStateuseReducer가 있다.

useReduceruseState와 동일하게 state를 관리하는 훅이다.

하지만, usestate의 상태변경 로직(setState)를 reducer를 통해 따로 분리하여 관리한다.


UseReducer와 UseState의 차이

1. UseState

import { useCallback, useState } from 'react';

export default function App() {
  const [state, setState] = useState(0);

  const increment = useCallback(() => {
    setState(state+1);
  },[state]);
  
  const decrement = useCallback(() => {
    setState(state-1);
  },[state]);

  return (
    <>
      <h3>{state}</h3>
      <button
        onClick={increment}
      >
        Increase Counter
      </button>
      <button
        onClick={decrement}
      >
        Decrease Counter
      </button>
    </>
  );
}

2. UseReducer

import { useReducer } from 'react';

const reducer = (state, action) => {
  switch (action.type) {
    case 'INCREASE':
      return state + 1;
    case 'DECREASE':
      return state - 1;
  }
  throw new Error('[ERROR] unknown action type');
};

export default function App() {
  const [state, dispatch] = useReducer(reducer, 0);

  return (
    <>
      <h3>{state}</h3>
      <button
        onClick={() => {
          dispatch({ type: 'INCREASE' });
        }}
      >
        Increase Counter
      </button>
      <button
        onClick={() => {
          dispatch({ type: 'DECREASE' });
        }}
      >
        Decrease Counter
      </button>
    </>
  );
}

UseReducer를 사용하면 업데이트 로직을 간단하게 할 수 있는 것은 아니지만,

UseState와 달리 redcuer를 통해 React 컴포넌트 내부에서 복잡한 업데이트 로직을 분리할 수 있다는 것이 장점이다.

UseReducer를 사용하는 경우

변경하려는 state의 형태가 복잡할 때

const state = {
  name : 'Lee',
  age : 26,
  address : {
    country : 'Korea',
    city : 'Seoul'
  }
}

분산된 setState 로직을 한 곳에 모으고 싶을 때

reducer 함수는 컴포넌트 외부로 분리되어 있으며, 모든 setter 로직이 몰려 있기에,
state가 잘못 업데이트 되었을 때, reducer 함수만 확인해보면 되므로 유리하다.

0개의 댓글