Redux state 사용하기

Yerim Son·2023년 7월 4일
0

React

목록 보기
18/23

리덕스 로직 저장소

  • src/redux/index.js
// 리덕스 로직 저장소

import { legacy_createStore as createStore } from "redux";

const initialState = { counter: 0, showCounter: true}

const counterReducer = (state = initialState, action) => {
  if (action.type === "increment") {
    return {
      counter: state.counter + 1,
      showCounter: state.showCounter
    };
  }

  if (action.type === "increase") {
    return {
      counter: state.counter + action.amount,
      showCounter: state.showCounter
    };
  }

  if (action.type === "decrement") {
    return {
      counter: state.counter - 1,
      showCounter: state.showCounter
    };
  }

  if(action.type === 'toggle'){
    return{
        counter: state.counter,
        showCounter: !state.showCounter
    }
  }
  return state;
};
const store = createStore(counterReducer);

export default store;

위가 내 리덕스 로직 저장소인데, 필기할 게 생겨서 싸악 들고 왔다.
아래를 보자.

const counterReducer = (state = initialState, action) => {
  if (action.type === "increment") {
    return {
      counter: state.counter + 1,
      showCounter: state.showCounter // 요게 없다면...? 안된다고요. 아래 설명
    };
  }

위는 increment를 말하고 있는데 왜 showCounter도 냅다 끼어드냐?

이유는 redux는 기존 state를 대체하는 완전히 새로운 객체, 새 '스냅샷'을 반환해야 한다.

때문에 위의 reducer에서 return하는 것는 기존 state와 병합되는 것이 아닌 기존 state를 대체한다.


1.

🤔 만약 저기서 showCounter를 빼면 어떻게 될까?

const counterReducer = (state = initialState, action) => {
  if (action.type === "increment") {
    return {
      counter: state.counter + 1,
      //showCounter를 뺐다.
    };
  }

이렇게 showCounter를 뺀다면, Counter.js에서 increment 버튼을 클릭했을 때 toggle마저 닫혀버리게 된다.

왜 counter toggle마저 닫히는 거지? 나는 toggle설정을 주지 않았는데?

바로 이유는,
위의 코드에서 showCounter를 설정하지 않았기 때문에, showCounter는 객체에서 제거되고, undefined값을 갖게 되고, 결국 false로 간주되기 때문이다.


결론!

예전 state를 '덮어 쓰는' 방식이기 때문에, state를 업데이트할 때는 항상 다른 state도 꼬옥 설정해줘야 한다.



2.

🤔 counter 자체를 증가시켜버리면 안되나?

const counterReducer = (state = initialState, action) => {
  if (action.type === "increment") {
    state.counter++;
    return state;
    };
  }

그냥 위의 코드처럼
state를 변경하고 그 거 return 해주면 되는 거 아니야?

안돼!!!!!!!!!!!!!!!!!
redux에선 절.대. 기존의 state를 변경해서는 안되는 거야

대신 새로운 객체를 반환하여 state 객체를 재정의하지.
아래처럼 말이야.

const counterReducer = (state = initialState, action) => {
  if (action.type === "increment") {
    return {
      counter: state.counter + 1,
      showCounter: state.showCounter 
    }; //이렇게 새로운 객체를 반환해서 state 재정의!
  }

편안~~

항상 새로운 객체, 새 값을 반환해야 한다는 것
잊쥐마❤️

만약 그렇지 않으면 버그가 나타날 수도, 디버깅도 힘들고 등등..ㅜ

결론

  • 절대 기존의 state를 변형시켜선 안된다.
  • 항상 새로운 객체를 반환하여 state 객체를 재정의해야 한다.

+ 추가

위의 코드는 reduxjs/toolkit 설치 후 더 세련되게 바뀔 예정이다.
reduxjs toolkit을 사용하면~~~ 반전..이라고 해야하나
훨씬 더 쉽게 reducer를 작성할 수 있게 된다
커밍쑨❤️ 두근두근

0개의 댓글