Redux

JavaScript 애플리케이션에서 상태 관리를 쉽게 하기 위해 사용되는 라이브러리

애플리케이션의 모든 상태를 하나의 중앙 저장소(store)에서 관리하며,

이를 통해 컴포넌트 간의 데이터 전달과 상태 변경을 일관되게 처리할 수 있다.

 

 

  • Store: 애플리케이션의 모든 상태(State)를 관리하는 객체
  • Action: 상태 변경을 요청하는 객체로, 액션 타입(type)과 데이터(payload)를 포함
  • Reducer: 액션을 처리하고 새로운 상태를 반환하는 순수 함수, 이전 상태와 액션을 받아서 새로운 상태를 반환하는 역할
  • Dispatch: 액션을 store에 전달하는 함수
  • State: 현재 애플리케이션의 상태를 의미하며, store에서 관리

Redux 라이브러리 설치 명령어

// redux 설치

// npm
npm install redux

// yarn
yarn add redux


// react redux 설치

// npm
npm install react-redux

// yarn
yarn add react-redux

Redux의 동작 흐름

액션 생성 → 액션 전달 → 리듀서 → 상태 업데이트

 

  • 액션 생성(Action Creation): 사용자가 어떤 이벤트를 트리거하면 액션이 생성
  • 액션 전달(Action Dispatch): 생성된 액션은 dispatch 메서드를 통해 리덕스 store로 전달
  • 리듀서(Reducer): store는 해당 액션을 리듀서로 전달하고, 리듀서는 액션에 맞는 새로운 상태를 반환
  • 상태 업데이트(State Update): 새로운 상태가 store에 저장되며, 애플리케이션 UI가 이를 기반으로 업데이트

Redux의 명령어

  • createStore(): Redux 스토어 생성
  • dispatch(): 액션을 스토어로 전달
  • subscribe(): 상태 변화 감지
  • getState(): 현재 상태 조회
  • combineReducers(): 여러 리듀서 결합
  • applyMiddleware(): 미들웨어 적용
  • bindActionCreators(): 액션 생성 함수 바인딩
  • compose(): 함수 합성

Redux의 사용 예시

 

Local (VScode)

 

action.js

// action.js

// 액션 타입 정의
export const INCREMENT = 'INCREMENT';
export const DECREMENT = 'DECREMENT';

// 액션 생성 함수
export const increment = () => {
  return {
    type: INCREMENT
  };
};

export const decrement = () => {
  return {
    type: DECREMENT
  };
};

 

reducer.js

// reducer.js

import { INCREMENT, DECREMENT } from './action';

// 초기 상태 정의
const initialState = {
  count: 0
};

// 리듀서 함수
const counterReducer = (state = initialState, action) => {
  switch (action.type) {
    case INCREMENT:
      return {
        ...state,
        count: state.count + 1
      };
    case DECREMENT:
      return {
        ...state,
        count: state.count - 1
      };
    default:
      return state;
  }
};

export default counterReducer;

 

store.js

// store.js

import { createStore } from 'redux';
import counterReducer from './reducer';

// 스토어 생성
const store = createStore(counterReducer);

export default store;

 

App.js

// App.js

import React from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { increment, decrement } from './action';

const App = () => {
  // Redux store에서 상태 가져오기
  const count = useSelector((state) => state.count);
  const dispatch = useDispatch();

  return (
    <div>
      <h1>Counter: {count}</h1>
      <button onClick={() => dispatch(increment())}>Increment</button>
      <button onClick={() => dispatch(decrement())}>Decrement</button>
    </div>
  );
};

export default App;

 

해당 예시 폴더구조

더보기

my-redux-app/

├── public/
│   └── index.html     # React 애플리케이션이 렌더링될 HTML 파일

├── src/
│   ├── actions/
│   │   └── counterActions.js   # Redux 액션 생성자 정의
│   │
│   ├── reducers/
│   │   └── counterReducer.js   # Redux 리듀서 정의
│   │
│   ├── store/
│   │   └── store.js            # Redux 스토어 설정
│   │
│   ├── components/
│   │   └── Counter.js          # Counter 컴포넌트 (React Component)
│   │
│   └── App.js                  # 최상위 App 컴포넌트
│   └── index.js                # ReactDOM을 통해 App 렌더링

├── package.json                # 프로젝트 의존성 정보
└── README.md                   # 프로젝트 설명

 

 

결과(codepen)

See the Pen redux by 유상현 (@ltfsrwdf-the-selector) on CodePen.

 

Redux 장점

 

  • 예측 가능한 상태 관리: 모든 상태 변경이 액션과 리듀서를 통해 이루어지므로 애플리케이션 상태를 예측하기 쉽다.
  • 중앙 집중화된 상태: 상태가 한 곳에 모여 있어, 상태를 쉽게 관리하고 디버깅할 수 있다.
  • 확장성: 대규모 애플리케이션에서도 일관된 패턴을 유지할 수 있다.

※ Redux는 복잡한 상태 관리를 간소화하는 데 유용하다. but 무조건 사용해야하는 것도 아니다.

 

+ Recent posts