미라클 메모리

목차

리덕스는 어떻게 활용할까?

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

상태관리를 컴포넌트 외부로 분리해서 상태관리를 효율적으로 진행한다. 0번째 인덱스는 useState처럼 사용가능하고, dispatch함수는 상태 변화를 일으킨다. 일어난 상태 변화를 reducer가 처리해주는 역할을 한다. 그리고 useReducer의 두번째 인수는 state의 초기값을 의미한다.

  1. disaptch 상태 변화 발생
  2. reducer 함수 호출

reducer 함수

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];
		.....
    default:
      return state;
  }
};

첫 번째 인수로 가장 최신의 state를 받고 두 번째는 action 객체를 전달받는다. state는 useReducer의 두번째 인수로 정한 초기값이다. action.type의 return 값은 새로 생성되는 상태값이 된다. 예를들어 아래와 같은 코드가 실행된다고 가정해보자

const onCreate = (author, content, emotion) => {
    dispatch({
      type: "CREATE",
      data: { author, content, emotion, id: dataId.current },
    });
  };

onCreate 함수가 실행이 되고 dispatch 함수가 실행이 된다. 이때 action객체에 type: ”CREATE”가 전달이 되고, newItem에 새로운 created_date를 추가한다.

return [newItem, ...state];

이때 새롭게 생성된 newItem은 기존의 상태값과 동시에 배열로 반환된다. 이 상태값이 기본 상태값으로 전달된다.

Create, Remove, Edit

// CREATE
  const onCreate = (author, content, emotion) => {
    dispatch({
      type: "CREATE",
      data: { author, content, emotion, id: dataId.current },
    });
  };

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

  // EDIT
  const onEdit = (targetId, newContent) => {
    dispatch({
      type: "EDIT",
      targetId,
      newContent,
    });
  };

onCreate

  const onCreate = (author, content, emotion) => {
    dispatch({
      type: "CREATE",
      data: { author, content, emotion, id: dataId.current },
    });
  };