[React] 14. useReducer Hook을 통한 상태 업데이트 로직 분리

백괴·2021년 9월 22일
0

리액괴

목록 보기
12/14
post-thumbnail

잘못 된 내용에 대한 지적은 언제든 환영입니다.

useReducer

  • 상태 업데이트 로직을 컴포넌트와 분리할 수 있다. 컴포넌트 바깥에 작성하거나 외부 파일에서 작성하여 import 할 수 있다.
    👉 컴포넌트 외부에서 상태 관리를 할 수 있다
  • Context API와 응용할 경우 전역적 상태 관리가 가능하다. 이에 대한 내용은 이후에 다룬다.
  • 컴포넌트에서 관리하는 상태가 여러개이고 복잡한 구조일 경우 이를 사용하는 편이 유리하다.

useReducer 함수의 구조

const [state, dispatch] = useReducer(reducer, initialState);
  • state : 현재 상태
  • dispatch : 액션을 발생시키는 함수이며, reducer 함수의 두 번째 파라미터에 객체를 전달한다.
   // 보통 type에 상태 업데이트 로직을 구분하는 고유의 문자열을 넣는다.
   dispatch({
     type: "ON_INCREASE",
     number: 1,
   });
  • reducer : 상태 업데이트 로직을 담은 함수
  • initialState : 초기 상태

reducer 함수의 구조

function reducer(state, action) {...}
  • state : 현재 상태
  • action : dispatch 함수를 통해 받은 객체
   // 보통 switch-case문을 통해 action.type 값에 따라 수행 할 상태 업데이트 로직을 결정한다.
   function reducer(state, action) {
     switch (action.type) {
       case "ON_INCREASE":
         return {
           ...state,
           number: state.number + action.number,
         };
       default:
         return state;
     }
   }

useReducer 예제

  • '+1', '-1' 버튼을 눌러, 화면에 띄워져 있는 숫자를 사칙연산하는 예제
   import { useReducer } from "react";

   // 상태 업데이트 로직을 담은 reducer 함수
   function reducer(state, action) {
     switch (action.type) {
       case "ON_INCREASE":
         return state + action.number;
       case "ON_DECREASE":
         return state - action.number;
       default:
         return state;
     }
   }

   function App() {
     // useReducer()
     const [number, dispatch] = useReducer(reducer, 0);

     /* 더하기, 빼기 이벤트 함수에는,
     각각 필요한 로직을 사용하기 위해 필요한 값들이 담긴 객체를 dispatch 함수로 넘겨주었다. */
     const onIncrease = () => {
       dispatch({
         type: "ON_INCREASE",
         number: 1,
       });
     };

     const onDecrease = () => {
       dispatch({
         type: "ON_DECREASE",
         number: 1,
       });
     };

     return (
       <div>
         <h1>{number}</h1>
         <button onClick={onIncrease}>+1</button>
         <button onClick={onDecrease}>-1</button>
       </div>
     );
   }

   export default App;

References
"20. useReducer 를 사용하여 상태 업데이트 로직 분리하기" .velopert
"React Hooks : useReducer() 함수" .xiubindev

0개의 댓글