Notice
Recent Posts
Recent Comments
«   2025/07   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
Archives
Today
Total
관리 메뉴

AI기록장

React_기초다지기_하루정리(복잡한 상태변화 로직 분리 - useReduce) 본문

React

React_기초다지기_하루정리(복잡한 상태변화 로직 분리 - useReduce)

SanL 2023. 5. 31. 02:23

React


⚑목표 : 복잡하고 많은 상태 변화 로직을 분리해보자!


[useReducer]

  • 컴포넌트에서 상태변화 로직을 분리하여 컴포넌트를 보다 가볍게해줌.

//reducer 함수는 두개의 파라미터를 받음(0,0)
그 reducer가 반환하는 값이 새로운 상태변화의 값이된다!
마찬가지로, 액션을 일으키는 useReducer도 두개의 바라미터를받고 그 중 첫번째 파라미터는
액션을 처리해주는(reducer,초기값)형태로 불러주어야함

const Counter = () =>{
  const [count, dispatch] = useReducer(reducer,1);

  return(
    ...
  );
};

const reducer = (state,action) => {
  ...
}

useReducer 같은 경우는 위 코드를 보면서 사용방법에 대해 설명해보면,
counter 안에 들어있는 count는 useState에서 사용했던거처럼 상태를 사용할 수 있으며,
두번째로 반환받는 dispatch는 상태를 변화시키는action 발생시키는 변수라고 생각하면 된다.
또한,useReducer에서 첫번째 파라미터로 전달받는 reducer는 action이 일어난 것을 처리해주는 변수이다. 즉,
위 코드에서는 dispatch가 호출이 되면, reducer함수로 가게되고 일어난 액션을 처리하게되는 것
두번째 파라미터의 인자는 count의 초기값이다!


[이전의 코드들을 업그레이드 시켜보자!]

**위에서의 useReducer을 적용해 앞선 시간들의 코드들을 수정해보자!

import { useCallback, useMemo, useEffect, useRef, useReducer } from "react";
import "./App.css";
import DiaryEditor from "./DiaryEditor";
import DiaryList from "./DiaryList";

const reducer = (state, action) => {
  switch (action.type) {
    case "INIT": {
      return action.data;
    }
    case "CREATE": {
      const created_date = new Date().getTime();
      const newItem = {
        ...action.data,
        created_date,
      };
      return [newItem, ...state];
    }
    case "REMOVE": {
      return state.filter((it) => it.id !== action.targetId);
    }
    case "EDIT": {
      return state.map((it) =>
        it.id === action.targetId ? { ...it, content: action.newContent } : it
      );
    }
    default:
      return state; // 값이 안바뀌는 경우
  }
};

function App() {
  // const [data, setData] = useState([]); //우리는 여기에 일기 리스트를 저장할 것이기 때문에 빈배열

  const [data, dispatch] = useReducer(reducer, []);

  const dataId = useRef(0);

  const getData = async () => {
    const res = await fetch(
      "https://jsonplaceholder.typicode.com/comments"
    ).then((res) => res.json());

    const initData = res.slice(0, 20).map((it) => {
      return {
        author: it.email,
        content: it.body,
        emotion: Math.floor(Math.random() * 5) + 1,
        created_date: new Date().getTime(),
        id: dataId.current++,
      };
    });
    dispatch({ type: "INIT", data: initData }); // reducer는 액션 객체를 받는데 type이 "init"이고, 그 데이터에 필요한 값은 initdata이다.
  };

  useEffect(() => {
    getData();
  }, []);

  //리스트에 작성하는 작성자, 감정, 내용들을 onCreate를이용하여 저장
  const onCreate = useCallback((author, content, emotion) => {
    dispatch({
      type: "CREATE",
      data: { author, content, emotion, id: dataId.current },
    });

    dataId.current += 1; // dataId가 하나씩 증가하도록 만들어줌
  }, []);

  const onRemove = useCallback((targetId) => {
    dispatch({ type: "REMOVE", targetId });
  }, []);

  const onEdit = useCallback((targetId, newContent) => {
    // 특정 데이터를 수정하는 함수
    dispatch({ type: "EDIT", targetId, newContent });
  }, []);

  const getDiaryAnalysis = useMemo(() => {
    const goodCount = data.filter((it) => it.emotion >= 3).length;
    const badCount = data.length - goodCount;
    const goodRatio = (goodCount / data.length) * 100;
    return { goodCount, badCount, goodRatio };
  }, [data.length]);

  const { goodCount, badCount, goodRatio } = getDiaryAnalysis;

  return (
    <div className="App">
      <DiaryEditor onCreate={onCreate} />
      <div>전체 일기 : {data.length}</div>
      <div>기분 좋은 일기 개수 : {goodCount}</div>
      <div>기분 나쁜 일기 개수 : {badCount}</div>
      <div>기분 좋은 일기 비율 :{goodRatio}</div>
      <DiaryList onEdit={onEdit} onRemove={onRemove} diaryList={data} />
    </div>
  );
}

export default App;

//DiaryList 컴퍼넌트는 리스트를 랜더링하는 역활
//filter 을 이용하여 특정 배열만 제외하고 다시 배열을 만들 수 있음

// useEffect같은 경우는 두개의 파라미터를 받아오고
//useEffect(()={
// callback 함수
//},[])
//[]은 Dependency array 의존성 배열
// 이 배열내에 들어있는 값이 변화하면 함수가 수행됨.