[React] useReducer 정리

Nowod_K·2022년 6월 28일
0

리액트 자습서 중 useReducer 부분을 참고하였습니다.
https://ko.reactjs.org/docs/hooks-reference.html#usereducer

useReducer

useReducer는 useState의 대체함수이다.
일반적으로 (state, action) => newState 형태로 reducer를 생성하고 dispatch로 메서드에 따라 state를 반환한다.

const initialState = {count: 0};

function reducer(state, action) {
  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);
  return (
    <>
      Count: {state.count}
      <button onClick={() => dispatch({type: 'decrement'})}>-</button>
      <button onClick={() => dispatch({type: 'increment'})}>+</button>
    </>
  );
}
  • useReducer 선언 시 2번째 인자로 초기값을 할당할 수 있다.
  • dispatch를 통해 객체를 전달하면서 해당 객체가 action으로 넘어온다.
  • state를 통해 reducer에 정의된 값들을 접근할 수 있다. (ex state.count)

useReducer 간단 정리

  1. initialState에 넣어줄 초기값을 생성한다.
  2. reducer 함수를 생성한다. (인자는 state, action)
  3. switch문을 통해 action별 코드를 작성한다.
  4. const [state, dispatch] = useReducer(reducer, initialState)로 reducer를 선언한다.
  5. dispatch를 통해 action에 값을 전달한다.
  6. state를 통해 값을 접근한다.

useReducer를 활용하면 useState보다 더 복잡한 로직을 만들 수 있다.

profile
개발을 좋아하는 마음과 다양한 경험을 토대로 좋은 개발자가 되고자 노력합니다.

0개의 댓글