UseReducer[React]

SnowCat·2023년 3월 10일
0

React - Hooks

목록 보기
7/7
post-thumbnail

useReducer란?

const [state, dispatch] = useReducer(reducer, initialArg, init);
  • useState를 대체할 수 있는 함수
  • (state, action) => newState의 형태로 reducer를 받고, dispatch 메서드와 짝의 형태로 state를 반환함
  • 하위값이 많은 복잡한 static logic을 만드는 경우나 state가 다른 state에 의존하는 경우 useReducer를 유용하게 사용 가능
  • useReducer는 콜백 대신 dispatch를 통해 state를 업데이트 할 수 있기 때문에 성능 최적화에도 도움이 됨
  • state와 비슷하게 Hook에서 동일한 값을 반환하면 자식을 리렌더링하거나 effect를 발생시키지 않음에 유의

example

const initialState = {count: 0};

// state action 객체를 입력으로 받음
function reducer(state, action) {
  //action에 따라 동작할 행동 선택 가능
  switch (action.type) {
    case 'increment':
      return {count: state.count + 1};
    case 'decrement':
      return {count: state.count - 1};
    default:
      throw new Error();
  }
}

function Counter() {
  // useReducer는 reducer 함수, 초기 상태값, (지연생성시) 초기화 함수를 받음
  const [state, dispatch] = useReducer(reducer, initialState);
  return (
    <>
      Count: {state.count}
      /* dispatch 사용을 통해 reducer 함수 작동 */
      <button onClick={() => dispatch({type: 'decrement'})}>-</button>
      <button onClick={() => dispatch({type: 'increment'})}>+</button>
    </>
  );
}

초기 state 설정 방법

  • 처음 설정시 reducer와 초기 상태값을 전달하면 됨
const [state, dispatch] = useReducer(
  reducer,
  {count: initialCount}
);
  • reducer의 초기화가 필요한 경우 초기상태값 이후에 초기화 함수를 전달해주면 됨
function init(initialCount) {
  return {count: initialCount};
}

function reducer(state, action) {
  switch (action.type) {
    case 'increment':
      return {count: state.count + 1};
    case 'decrement':
      return {count: state.count - 1};
    // init함수를 활용해 초기화 진행
    case 'reset':
      return init(action.payload);
    default:
      throw new Error();
  }
}

function Counter({initialCount}) {
  // 초기 state는 지연되서 생성되며, reducer 외부에서 초기 state 계산이 가능해짐
  const [state, dispatch] = useReducer(reducer, initialCount, init);
  return (
    <>
      Count: {state.count}
      <button
        onClick={() => dispatch({type: 'reset', payload: initialCount})}>
        Reset
      </button>
      <button onClick={() => dispatch({type: 'decrement'})}>-</button>
      <button onClick={() => dispatch({type: 'increment'})}>+</button>
    </>
  );
}

출처:
https://ko.reactjs.org/docs/hooks-reference.html#usereducer

profile
냐아아아아아아아아앙

0개의 댓글