[리팩토링]_depth 깊은 상태, Redux로 관리

hanseungjune·2023년 7월 27일

리팩토링

목록 보기
2/25
post-thumbnail

Redux로 바꾼 이유는?

상태관리를 할 때, 해당 컴포넌트에서 모두 마무리하면 다행이지만, 보통은 props를 하게 되어있다. 그래서 depth가 깊어지곤하여 코드의 복잡도가 높아졌었었다. 그래서 이를 해결하기 위해서 전역으로 상태관리를 해야겠다는 생각이 들었고, 그리하여 Redux를 사용하게 되었다.

작성 코드 및 설명

rootReducer.js

import { combineReducers } from "redux";
import { audioReducer } from "./reducers/audioReducer";
import qrCodeReducer from "./reducers/qrdataReducer";

export default combineReducers({
  audio: audioReducer,
  qrCode: qrCodeReducer,
});

Redux의 combineReducers 함수를 사용하여 애플리케이션의 모든 리듀서를 하나의 루트 리듀서로 결합합니다. 여기서는 두 가지 리듀서 audioReducer와 qrCodeReducer가 있습니다. 이 루트 리듀서는 이후 Redux store를 생성하는데 사용됩니다.

store.js

import { createStore } from 'redux';
import rootReducer from './rootReducer'; 

const store = createStore(rootReducer);

export default store;

Redux store를 생성합니다. Store는 애플리케이션의 전체 상태 트리를 보유하는 곳입니다. 이 내부의 상태를 변경하는 유일한 방법은 액션을 디스패치하는 것입니다.

index.js

import React from "react";
import { render } from "react-dom";
import { Provider } from "react-redux";
import App from "./App";
import store from "./kiosk/redux/store";

// MSW 세팅
if (process.env.NODE_ENV === "development") {
  const { worker } = require("./mocks/browser");
  worker.start();
}

const container = document.getElementById("root");
render(
  <Provider store={store}>
    <App />
  </Provider>,
  container
);

일반적으로 React 애플리케이션의 진입점입니다. 주요 App 컴포넌트를 렌더링하고 Redux Provider로 감싸서 모든 컴포넌트 트리에서 store를 이용할 수 있도록 합니다. 이 과정에서 앱이 개발 모드에서 실행 중인지 확인하고, 그렇다면 Mock Service Worker (MSW)를 시작하여 개발 환경에서 API 요청을 처리합니다.

audioAction.js

export const SET_AUDIO = 'SET_AUDIO';
export const SET_PLAYING = 'SET_PLAYING';

export const setAudio = (audio) => ({
  type: SET_AUDIO,
  payload: audio
});

export const setPlaying = (playing) => ({
  type: SET_PLAYING,
  payload: playing
});

Redux 상태의 audio 부분에 대한 액션 생성자를 포함하고 있습니다. 액션 생성자는 액션을 반환하는 함수로, 액션은 type 속성과 선택적으로 추가 데이터를 포함하는 payload 속성을 가진 객체입니다.

audioReducer.js

import { SET_AUDIO, SET_PLAYING } from "../actions/audioActions";

// reducer
const initialState = {
  audio: null,
  playing: false,
};

export const audioReducer = (state = initialState, action) => {
  switch (action.type) {
    case SET_AUDIO:
      return { ...state, audio: action.payload };
    case SET_PLAYING:
      return { ...state, playing: action.payload };
    default:
      return state;
  }
};

Redux 리듀서는 현재 상태와 액션을 인자로 받아 액션의 유형에 따라 새로운 상태를 반환하는 함수입니다. 이 파일은 상태의 audio 부분에 대한 리듀서를 포함하고 있습니다. SET_AUDIO와 SET_PLAYING 액션에 응답하여 audio 또는 playing 속성이 업데이트된 새로운 상태를 반환합니다.

qrdataAction.js

export const SET_QR_CODE = 'SET_QR_CODE';
export const RESET_QR_DATA = 'RESET_QR_DATA';

export const setQRCode = (data) => ({
    type: SET_QR_CODE,
    payload: data
});

export const resetQRCode = () => ({
    type: RESET_QR_DATA,
});

qrCode 상태 부분에 대한 액션 생성자를 포함하고 있습니다. audioAction.js와 마찬가지로 이 함수들은 액션 객체를 반환합니다.

qrdataReducer.js

import { RESET_QR_DATA, SET_QR_CODE } from "../actions/qrdataAction";

const initialState = {
  data: "",
};

export default function qrCodeReducer(state = initialState, action) {
  switch (action.type) {
    case SET_QR_CODE:
      return {
        ...state,
        data: action.Payload,
      };
    case RESET_QR_DATA:
      return {
        ...state,
        data: initialState.data,
      };
    default:
      return state;
  }
}

이 파일은 상태의 qrCode 부분에 대한 리듀서를 포함하고 있습니다. SET_QR_CODE와 RESET_QR_DATA 액션에 응답하여 상태를 업데이트합니다. 특히, RESET_QR_DATA 액션은 data 속성을 초기 상태로 다시 설정합니다.

간단한 Redux 상태 관리 시스템을 구성하며, 상태의 두 "조각"인 audio와 qrCode를 처리합니다. 각 조각에는 자체 액션과 리듀서가 있습니다. 이렇게 Redux 코드를 조직하는 패턴은 Redux에서 일반적으로 볼 수 있는 패턴으로, 상태의 다른 부분이 어떻게 관리되는지 이해하는 데 도움이 될 수 있습니다.

profile
필요하다면 공부하는 개발자, 한승준

0개의 댓글