관리 메뉴

제뉴어리의 모든것

reducer 사용 법 본문

리액트

reducer 사용 법

제뉴어리맨 2024. 3. 30. 17:10

 

준비

import React, { useReducer } from "react";

 


 

사용 예

import React, { useReducer } from "react"; //reducer 사용하기 위해 import 시킴


//reducer의 실제 내용 정의
//state : 현재 state값
//action : dispatch로 reducer 호출할때 전달받은 인자
//리턴값 : 최종적으로 변경시킬 state 값
const reducer = (state, action) => { 
  let newState = [];
  switch (action.type) {
    case "INIT":
      return action.data;
    case "CREATE":
      newState = [action.data, ...state];
      break;
    case "EDIT":
      newState = state.map((it) =>
        it.id === action.targetId ? { ...action.data } : it
      );
      break;
    case "REMOVE":
      newState = state.filter((it) => it.id !== action.targetId);
      break;
    default:
      return state;
  }

  localStorage.setItem("diary", JSON.stringify(newState));
  return newState;
};


function App() {
	//reducer 생성, 
    //data : reducer가 관리하는 state
    //dispatch : reducer를 호출하는 명칭, 아래에서 dispatch()호출을 하지만 실제 구동되는 함수 내용은 위에 reducer 내용임
   	//reducer : 위에서 정의한 reducer를 설정
    //[] : 초기 값
  const [data, dispatch] = useReducer(reducer, []); 

:
:

 useEffect(() => {
    const localData = JSON.parse(localStorage.getItem(`diary`));

    if (localData) {
      dispatch({ 		//reducer 호출, 인자로 전달 되는 객체는 모두 reducer에서 action 인자로 받게 된다.
        type: "INIT",
        data: localData,
      });
    }
  }, []);

}

 


 

간략 설명

reducer는 결국 state 값을 변경시키기 위한 방법 중 하나이다.

reducer라는 state 값을 변경시키는 함수를 정의하고 해당 함수를 dispatch로 호출하여 실행시킨다.

그리고 dispatch가 리턴해야 하는 값은 수정할 state 값이다.

 


참고 유용 사이트

https://goddaehee.tistory.com/311