cs

Redux 원리와 동작 방식

ssoonn 2025. 2. 26. 16:21

0. Redux란?

js 애플리케이션의 상태 관리를 위한 라이브러리이며, 단방향 데이터 흐름을 통해 애플리케이션의 상태 변화를 예측 가능하게 만드는 패턴을 제공한다.

 

React만으로 작은 애플리케이션을 구축할 때는 useState나 useReducer와 같은 내장 훅으로 충분할 수 있다.

다만 애플리케이션 규모가 커지고 다양한 컴포넌트가 동일한 상태를 공유해야 할 때 복잡성이 증가한다.

→ Redux는 상태 관리의 복잡성을 해결하는 효과적인 방법을 제공한다고 함!

 

1. 핵심 원리

Single Source of Truth

애플리케이션의 모든 상태는 하나의 스토어(store)에 있는 객체 트리에 저장된다.

// 스토어는 다음과 같은 하나의 큰 상태 객체를 관리한다.
{
  theme: {
    color: 'black',
    desc: '검정 테마'
  }
}

State is Read-Only

상태는 읽기 전용이며, 상태를 변경하려면 "액션"을 발생시켜야 한다.

이는 뷰나 네트워크 콜백이 직접 상태를 수정하는 것을 방지하고, 모든 change가 중앙 집중적으로 수행되도록 한다.

// 올바른 방법 - 액션 디스패치를 통한 상태 변경
store.dispatch({ type: 'theme/change' });

// 잘못된 방법 - 직접 상태 변경
store.state.theme.color = 'white'; // 이렇게 하면 안 됨!!!!!

Changes are Made with Pure Functions

상태 트리가 액션에 의해 어떻게 변경되는지 명시하기 위해 reducer 함수를 작성한다.

function themeReducer(state = { color: 'black', desc: '검정 테마' }, action) {
  switch (action.type) {
    case 'theme/change':
      if (state.color === 'black') {
        return { color: 'white', desc: '하양 테마' };
      } else {
        return { color: 'black', desc: '검정 테마' };
      }
    case 'theme/modify':
      return { 
        color: action.payload.color, 
        desc: action.payload.desc 
      };
    default:
      return state;
  }
}

 

2. 구성 요소 (용어)

1. Action

애플리케이션에서 스토어로 데이터를 보내는 정보 패킷이다. type 속성 필수!

  • type 속성: 필수. 리듀서가 어떤 상태를 변경해야하는지 알려줌.
  • payload 속성: 옵션. 액션과 함께 전달되는 데이터를 담는 속성.
// 기본 액션 객체
{ 
  type: 'theme/modify',
  payload: {
    color: 'red',
    desc: '빨강 테마'
  }
}

2. Action Creator

액션 객체를 반환하는 함수.

// 액션 생성자 함수
function changeTheme() {
  return { type: 'theme/change' };
}

function modifyTheme(color, desc) {
  return {
    type: 'theme/modify',
    payload: { color, desc }
  };
}

// 사용 예
dispatch(changeTheme());
dispatch(modifyTheme('red', '빨강 테마'));

 

3. Reducer

 previous state와 action을 받아 새로운 state를 반환하는 함수.

 

특징:

  • 불변성: 상태를 변경하지 않고 새로운 상태 객체를 반환
  • 순수 함수: 동일한 입력에 대해 항상 동일한 출력을 반환
  • 부수 효과 x: API 호출, 랜덤 값 생성 등 금지
// 테마 리듀서 확장 예제
function themeReducer(state = { color: 'black', desc: '검정 테마' }, action) {
  switch (action.type) {
    case 'theme/change':
      // 불변성을 유지하며 새 객체 반환
      return {
        ...state,
        color: state.color === 'black' ? 'white' : 'black',
        desc: state.color === 'black' ? '하양 테마' : '검정 테마'
      };
    case 'theme/modify':
      // 페이로드에서 받은 값으로 새 객체 생성
      return {
        ...state,
        color: action.payload.color,
        desc: action.payload.desc
      };
    default:
      return state;
  }
}

 

 

4. Store

상태를 저장하는 js 객체이다. (=상태 트리)

 

특징

  • redux 애플리케이션에는 하나의 스토어만 있다.
  • 스토어에 있는 상태를 변경하기 위해선 액션을 디스패치 해야한다.
    • 액션을 디스패치하다 = 상태 변경을 위한 명령(액션)을 시스템에 보내다(디스패치)
    • Redux에서 상태를 변경하려면 직접 상태를 수정할 수 없고, 반드시 액션이라는 객체를 통해 변경.
    • 이 액션 객체를 Redux 스토어에 보내는 과정이 "디스패치"

메소드

 

  • getState(): 현재 상태를 반환
  • dispatch(action): 액션을 디스패치하여 상태를 변경
  • subscribe(listener): 상태 변경 시 호출될 리스너를 등록
  • replaceReducer(nextReducer): 핫 리로딩이나 코드 분할을 위해 현재 리듀서를 교체

 

import { createStore } from 'redux';
import themeReducer from './reducers';

const store = createStore(themeReducer);

// 상태 조회
console.log(store.getState()); // { color: 'black', desc: '검정 테마' }

// 액션 디스패치
store.dispatch(changeTheme()); // 테마를 white로 변경

// 상태 변경 구독
const unsubscribe = store.subscribe(() => 
  console.log('상태가 업데이트되었습니다:', store.getState())
);

// 구독 해제
unsubscribe();

 

 

3. 동작 원리

사용자 인터랙션 → 액션 디스패치 → [미들웨어] → 리듀서 처리 → 스토어 업데이트 → UI 변경 → 사용자에게 표시

 

  1. 스토어 생성: 애플리케이션의 시작점에서 루트 리듀서를 사용하여 스토어를 생성
  2. 초기 상태 설정: 스토어가 생성될 때, 각 리듀서의 초기 상태가 설정
  3. 액션 디스패치: 사용자 인터랙션이나 API 응답 등의 이벤트가 발생하면, 해당하는 액션을 디스패치
  4. 리듀서 실행: 디스패치된 액션은 루트 리듀서로 전달되고, 리듀서는 현재 상태와 액션을 기반으로 새로운 상태를 계산
  5. 스토어 업데이트: 계산된 새로운 상태가 스토어에 저장
  6. 구독자 알림: 스토어는 등록된 모든 구독자(리스너)에게 상태 변경을 알림
  7. UI 업데이트: React 컴포넌트 등의 UI는 새로운 상태를 받아 화면을 업데이트

 

예시를 통한 이해

 

  1. UI에서 버튼이 클릭되면 Event Handler로 전달
  2. Event Handler는 Dispatch를 통해 액션을 Store로 전달
  3. Store 내부의 Reducer가 액션을 처리하여 새로운 State를 생성
  4. 업데이트된 State는 다시 UI로 전달되어 화면 갱신

 

 

 

 

 

ref

https://www.freecodecamp.org/news/what-is-redux-store-actions-reducers-explained/

 

What is Redux? Store, Actions, and Reducers Explained for Beginners

Redux is a predictable state container for JavaScript apps. So what does that really mean? If we dig deeper into this statement, we see that Redux is a state management library that you can use with any JS library or framework like React, Angular, or...

www.freecodecamp.org

https://redux.js.org/tutorials/fundamentals/part-2-concepts-data-flow

 

Redux Fundamentals, Part 2: Concepts and Data Flow | Redux

The official Redux Fundamentals tutorial: learn key Redux terms and how data flows in a Redux app

redux.js.org