전역상태 관리 Redux

2025. 4. 22. 18:54Coding Study/React

1. Redux 란

  Redux 는 react 에서 많이 사용하는 전역 상태관리 라이브러리

  상태를 한 곳에서 통합 관리할 수 있어서 예측가능한 방식으로 상태 관리 가능

  Redux 에서 공식적으로 추천하는 방법은 Redux Toolkit 을 사용하는 것이지만 Toolkit 사용 시에 Flux 패턴을

  확인하기가 힘들기 때문에 Redux를 활용하였다. 

 

 

  "Redux Toolkit은 Redux 로직을 작성하기 위한 표준 방식이 되도록 만들어졌고, 사용하기를 강력히 추천드립니다." 

  https://ko.redux.js.org/redux-toolkit/overview/

 

Redux Toolkit: 개요 | Redux

Redux Toolkit은 Redux 로직 작성을 위해 권장하는 방법입니다

ko.redux.js.org

 

"Redux Toolkit이 오늘날 Redux를 사용하는 방법인 이유"

https://ko.redux.js.org/introduction/why-rtk-is-redux-today/

 

Redux Toolkit이 오늘날 Redux를 사용하는 방법인 이유 | Redux

소개 > RTK가 현재의 Redux인 이유: RTK가 어떻게 Redux 코어를 대체하는지에 대한 상세 내용

ko.redux.js.org

 

 

 

2. 설치 방법

npm install redux react-redux

 

3. Redux 상태변경 데이터 흐름 ( Flux 패턴)  

  UI  →  Action  →  Dispatch  →  Reducer  →  Store  →  UI

 

    1) 사용자가 UI 에서 버튼 클릭

    2) 클릭이벤트로 Action 객체 생성

    3) Action 객체가 Dispatch 함수를 통해 Reducer 로 전달

    4) Reducer 에서 해당 Action 에 따라 Store(상태저장소) 업데이트

    5) 상태변경 후 UI 재 렌더링

 

4. Redux 구성요소

구성요소 설명
Action 상태를 어떻게 바꿀지 설명하는 객체
Dispatch Action을 Reducer로 보내는 함수
Reducer Action을 해석해 상태를 변경하는 함수
Store 전역 상태 저장소
Provider 리액트 앱에 Store를 연결해주는 컴포넌트
useSelector Store에서 상태를 꺼내올 때 사용
useDispatch Action을 보낼 Dispatch 함수를 꺼낼 때 사용

 

 

5. 적용 방법 (예제 : 카운터 앱 )

  1)  액션 정의 

      나중에 dispatch 로 Action 을 전달 시 객체를 쉽게 생성하기 위한 함수 이므로 다른파일에 저장 시에는 꼭 export 해주자

const increment = { type: 'increment' };
const decrement = { type: 'decrement' };

 

 2) Reducer 작성

const counterReducer = (state = 0, action) => {     // state 초기값 0
  switch(action.type) {                             // action.type 이
    case 'increment': return state + 1;             // INCREMENT 일 경우 state + 1   
    case 'decrement': return state - 1;             //  DEVREMENT 일 경우 state + 1
    default: return state;	  // default 작성안할경우 case 조건이 아닐때 대참사(undefined 반환)
  }                           
};

 

 3) 스토어 생성

   위에서 생성한 Reducer 을 Store 에 저장 한다. 

   스토어를 통해 다른 컴포넌트에 전역으로 값을 전달 할 수 있다. 

   이것도 다른파일에 작성하였다면 export 해 준다. 

import { createStore } from 'redux';

const store = createStore(counterReducer);

 

 

4) Provider 로 하위 폴더 연결 

  생성된 스토어를 Povider 를 통해 하위 컴포넌트에 연결 한다. 

import { Provider } from 'react-redux';
import store from './store';

<Provider store={store}>
  <App />
</Provider>

 

 

5) 상태 사용 및 dispatch를 통한 상태 변경

  useSelector 를 통해 state 를 받아오고 , useDispatch를 통해 Action 을 전달 해 상태를 변경 한다.  

import { useSelector, useDispatch } from 'react-redux';

const count = useSelector(state => state);
const dispatch = useDispatch();

<button onClick={() => dispatch(increment)}>+</button>
<button onClick={() => dispatch(decrement)}>-</button>

 

 

원래 Action type 을 객체로 아래와 같이 전달 해 주지만 Action 정의 에서 함수로 간단하게 만들어서 위와 같이 작성도 가능하다.

<button onClick={() => dispatch({ type: 'increment' })}>+</button>
<button onClick={() => dispatch({ type: 'decrement' })}>-</button>

 

 

 

 

 

6. 여러개의 상태 관리

 1) Reducer 추가 작성

const counter2Reducer = (state = 0, action) => {
  switch (action.type) {
    case "increment2": return state + 1;
    case "decrement2": return state - 1;
    default:return state;
  }
};

 

 2) Reducer 합치기

 rootReducer 변수에 combineReducers 로 counterReducer 와 counter2Reducer 를 묶어 준다.

import { combineReducers } from 'redux';

const rootReducer = combineReducers({ counterReducer, counter2Reducer });

 

3) Store 생성 하여 rootReducer 전달

const store = createStore(rootReducer);

 

 4) 각각의 상태 꺼내오기

  state.[Reducer 이름] 으로 상태값을 받아온다. 

  Reducer 별로 각각의 Action 값은 다르기 때문에 상태 변경시 dispatch 는 위의 내용과 동일하게 작성 가능 하다.

const counter = useSelector((state) => state.counterReducer);
const counter2 = useSelector((state) => state.counter2Reducer);