[리액트] useReducer란?

navyjeongs·2022년 5월 17일
0

리액트-T.I.L

목록 보기
4/5
post-thumbnail

useReducer란?

  • React의 상태관리를 위한 Hook중 하나이다.
  • useState와 비슷하지만 컴포넌트와 컴포넌트 업데이트 로직을 분리할 수 있다는 장점이 있다.
  • Context API로 전역 값을 관리할 때 사용되는 Hook이다.

useReducer 사용법 :

const [state, dispatch] = useReducer(reducer, initialState);
state : 컴포넌트에서 사용할 수 있는 상태, dispatch : 액션을 발생시키는 함수이다.
useReducer의 첫 번째 파라미터 : reducer 함수, useReducer의 두 번째 파라미터 : 초기 상태

reducer 함수 :

function reducer(state, action) {
  // 새로운 상태 로직
  return nextState;
}

아래는 useReducer의 사용한 간단한 예시이다.

App.js

import React, { useReducer } from "react";

const App = () => {
  // reducer 함수는 state와 action을 parameter로 받는다.
  const reducer = (state, action) => {
    switch (action.type) {
      case "ADD_ONE": // dispatch를 통해 발생한 action이 ADD_ONE이라면
        return state + 1;
      case "SUB_ONE": // dispatch를 통해 발생한 action이 SUB_ONE이라면
        return state - 1;
      default:
        return state;
    }
  };

  const [num, dispatch] = useReducer(reducer, 0); // 초기값을 0으로 설정

  const Increase = () => {
    dispatch({ type: "ADD_ONE" });
  };

  const Decrease = () => {
    dispatch({ type: "SUB_ONE" });
  };

  return (
    <div>
      <h3>{num}</h3>
      <button onClick={Increase}>숫자 증가</button>
      <button onClick={Decrease}>숫자 감소</button>
    </div>
  );
};

export default App;

위의 코드를 간략하게 설명하자면 숫자 증가 버튼을 클릭하면 Increase함수가 호출되고 Increase 함수는 type이 ADD_ONE인 액션을 발생시킨다. 해당 액션은 현재 state에 +1을 한다. 코드의 결과는 아래와 같다.

주의할 점 : reducer 함수는 useReducer보다 위에서 초기화가 되어있어야 한다.

useState와 useReducer중 무엇을 쓰는 것이 좋을까?

  • 컴포넌트에서 관리하는 값이 많지 않다면 useState를 사용한다.
  • 만약 관리하는 값이 많다면 useReducer를 통해 관리하는 것이 편하다.
profile
Front-End Developer

0개의 댓글