[React] useReducer

박소정·2023년 12월 14일
1

React

목록 보기
17/26
post-thumbnail

useReducer이란? 🧐

useState를 대체할 수 있는 함수로 컴포넌트에서 상태 변화 코드를 쉽게 분리할 수 있다.
상태 변화 코드를 컴포넌트에서 분리한다는 말은 컴포넌트 내부에 작성했던 상태 변화 코드를 외부에 작성한다는 뜻이다.

👉 상태 변화 코드를 분리하려는 이유?

"하나의 컴포넌트 안에 너무 많은 상태 변화 코드가 있으면 가독성을 해쳐 유지 보수를 어렵게 만들기 때문입니다."

사용법 😀

const [count, dispatch] = useReducer(reducer, 0);
  • count

    state 변수
  • dispatch

    상태 변화 촉발 함수
  • useReducer(reducer, 0);

    생성자(상태 변화 함수, 초깃값)

예시 👏

먼저 useState와 useReducer의 차이점을 확인하기 위해 useState로 간단한 코드를 구현했다. (버튼을 활용하여 count를 증가 or 감소하는 코드)

useState 사용

import { useState } from "react";

function TestComp() {
  const [count, setCount] = useState(0);
  const onIncrease = () => {
    setCount(count + 1);
  };

  const onDecrease = () => {
    setCount(count - 1);
  };

  return (
    <div>
      <div>
        <bold>{count}</bold>
      </div>
      <div>
        <button onClick={onIncrease}>+</button>
        <button onClick={onDecrease}>+</button>
      </div>
    </div>
  );
}

export default TestComp;

useReducer 사용

컴포넌트 외부에 상태 변화 코드 구현을 해준다.

    import { useReducer } from "react";

    function reducer(state, action) {
      switch (action.type) {
        case "INCREASE":
          return state + action.data;
        case "DECREASE":
          return state - action.data;
        default:
          return state;
      }
    }
    
    function TestComp() {
      const [count, dispatch] = useReducer(reducer, 0);

      return (
        <div>
          <div>
            <bold>{count}</bold>
          </div>
          <div>
            <button onClick={() => dispatch({ type: "INCREASE", data: 1 })}>
              +
            </button>
            <button onClick={() => dispatch({ type: "DECREASE", data: 1 })}>
              -
            </button>
          </div>
        </div>
      );
    }

    export default TestComp;
  • 새로운 상태 변화 추가 (useReducer)

    count 값을 0으로 초기화 해주는 상태 관리를 추가했다.

    import { useReducer } from "react";

    function reducer(state, action) {
      switch (action.type) {
        case "INCREASE":
          return state + action.data;
        case "DECREASE":
          return state - action.data;
        case "INIT": //새로운 case 추가
          return 0;
        default:
          return state;
      }
    }
    function TestComp() {
      const [count, dispatch] = useReducer(reducer, 0);

      return (
        <div>
          <div>
            <bold>{count}</bold>
          </div>
          <div>
            <button onClick={() => dispatch({ type: "INCREASE", data: 1 })}>
              +
            </button>
            <button onClick={() => dispatch({ type: "DECREASE", data: 1 })}>
              -
            </button>
            // 새로운 button 추가
            <button onClick={() => dispatch({ type: "INIT" })}>0으로 초기화</button>
          </div>
        </div>
      );
    }

    export default TestComp;

0개의 댓글