아직도 Redux인가?
1. 상태 관리란?
7장에서 Context로 props drilling을 피하는 방법을 배웠습니다. 그런데 여러 컴포넌트가 같은 값을 읽고 고쳐야 하는 일이 많아지면, 값을 어디에 두고 누가 어떻게 고치게 할지가 새로운 문제가 됩니다. 이 값들을 한곳에 모아 정해진 방식으로만 고치게 하는 것이 상태 관리이고, Redux는 그 일을 하는 도구입니다. 값을 컴포넌트마다 useState로 따로 두는 방법과 달리 Redux는 앱 전체가 함께 쓰는(전역) 값을 맡습니다.
2. 아직도 Redux인가?
Redux는 오랫동안 React 상태 관리의 표준이었습니다. 그런데 지금도 Redux를 배워야 할까요? 먼저 숫자를 보겠습니다. 2026년 10월까지의 내려받기 횟수를 npm 레지스트리에서 직접 받아 그려 보았습니다.

가로축은 2023년 11월부터 2026년 10월까지, 세로축은 한 주 동안 내려받은 횟수(4주 평균, M은 백만)입니다. 파란 선(redux)이 오래 1위였지만 주황 선(zustand)이 꾸준히 따라붙어, 2026년 3월 30일이 있는 주부터는 zustand가 계속 위에 있습니다. 2026년 10월 말 기준 4주 평균은 zustand 약 5,700만, redux 약 4,250만, @reduxjs/toolkit 약 3,050만입니다.
두 가지를 함께 기억해 두세요. 첫째, redux 숫자에는 Redux Toolkit(@reduxjs/toolkit)을 설치할 때 함께 따라오는 몫이 들어 있으므로, Redux 계열 전체가 줄어든 것은 아닙니다. 둘째, 내려받기 횟수에는 자동 빌드(CI) 같은 몫이 섞여 있어 사용자 수와 같지 않습니다. 새 프로젝트에서는 가벼운 Zustand를 고르는 경우가 늘었지만, 이미 운영 중인 서비스에는 Redux가 남아 있는 경우가 많으므로 이 장에서 Redux의 동작 원리를 익혀 둘 가치가 있습니다. Zustand 같은 가벼운 도구도 "값을 한곳에 두고, 쓰는 컴포넌트가 구독한다"는 같은 뼈대를 쓰기 때문에, Redux를 이해하면 다른 도구도 빨리 읽힙니다.
3. Redux란?
공식 홈페이지에서 설명하고 있는 리덕스의 정의를 한 번 보도록 합시다.
Redux 공식 홈페이지리덕스는 리액트만을 위한 라이브러리는 아닙니다. React뿐만 아니라 Vue와도 잘 결합되며, 또한 순수 JS와도 결합이 됩니다. 설치 없이 실행할 수 있는 생활코딩의 간단한 예제를 통해 Redux의 속성을 알아봅시다.
3.1 바닐라와 함께 Redux 살펴보기
생활코딩은 CCL 라이선스 BY를 따르고 있습니다. 자료의 출처가 생활코딩임을 명시합니다. 자료가 이전 자료여서 Claude를 통해 현대 버전으로 수정하였습니다.
- 관련 영상 Redux - 생활코딩
- 백업 코드 생활코딩.zip
아래 코드는 리덕스를 사용하지 않은 코드입니다. 빨강·초록·파랑 컴포넌트가 하나씩 있고, 어느 컴포넌트의 fire 버튼을 누르든 세 컴포넌트의 배경색이 모두 그 색으로 바뀝니다.
<html>
<head></head>
<body>
<style>
.container {
border: 5px solid black;
padding: 10px;
}
</style>
<div id="red"></div>
<div id="green"></div>
<div id="blue"></div>
<script>
function red() {
document.querySelector('#red').innerHTML = `
<div class="container" id="component_red">
<h1>red</h1>
<input type="button" value="fire" onclick="
document.querySelector('#component_red').style.backgroundColor = 'red';
document.querySelector('#component_green').style.backgroundColor = 'red';
document.querySelector('#component_blue').style.backgroundColor = 'red';
">
</div>
`;
}
red();
function green() {
document.querySelector('#green').innerHTML = `
<div class="container" id="component_green">
<h1>green</h1>
<input type="button" value="fire" onclick="
document.querySelector('#component_red').style.backgroundColor = 'green';
document.querySelector('#component_green').style.backgroundColor = 'green';
document.querySelector('#component_blue').style.backgroundColor = 'green';
">
</div>
`;
}
green();
function blue() {
document.querySelector('#blue').innerHTML = `
<div class="container" id="component_blue">
<h1>blue</h1>
<input type="button" value="fire" onclick="
document.querySelector('#component_red').style.backgroundColor = 'blue';
document.querySelector('#component_green').style.backgroundColor = 'blue';
document.querySelector('#component_blue').style.backgroundColor = 'blue';
">
</div>
`;
}
blue();
</script>
</body>
</html>
버튼 하나가 세 컴포넌트를 직접 찾아가 고치고 있습니다. 노랑 컴포넌트를 하나 더 만들면 모든 버튼의 onclick에 한 줄씩을 더 써야 하고, 하나라도 빠뜨리면 그 컴포넌트만 색이 달라집니다. 값을 바꾸는 쪽이 값을 쓰는 쪽을 전부 알아야 하는 것이 문제입니다. Redux는 이 관계를 끊습니다. 버튼은 "색을 이렇게 바꿔 달라"는 요청만 한곳에 보내고, 각 컴포넌트는 그 한곳에서 값을 읽어 자기 모습을 그립니다.
아래 코드는 리덕스를 사용한 코드입니다. 설치 없이 사용할 수 있도록 CDN을 사용했습니다. 주석 제거 버전입니다. 이 장의 예제는 redux 4.0.1을 <script>로 불러옵니다. 최신 5.x는 이 방식으로 불러도 전역 Redux가 생기지 않으므로(cdnjs에는 모듈 파일만 올라 있습니다) 최신 주소를 붙이면 Redux is not defined가 나옵니다. 지금은 아래 주소 그대로 쓰고, 프로젝트에서는 npm install로 설치해 import합니다(10-5).
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>리덕스를 사용해서 상태 관리하기</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/redux/4.0.1/redux.js"></script>
<style>
.container {
border: 5px solid black;
padding: 10px;
}
</style>
</head>
<body>
<div id="red-component"></div>
<div id="green-component"></div>
<div id="blue-component"></div>
<div id="test-component"></div>
<script>
// 바리스타(상태, 주문서)
const reducer = (state, action) => {
// 초기 상태(state)를 정의
if (state === undefined){
return {
color: 'yellow'
}
}
// 주문서(action)에 따라 상태(state)를 변경
switch (action.type){
case 'CHANGE_COLOR':
return {
...state,
color: action.color
}
default:
return state;
}
}
// 커피숍
const store = Redux.createStore(
reducer,
// Redux DevTools Extension을 사용하기 위한 설정
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
);
// 주문을 받는 점원(주문서를 생성하는 액션 크리에이터 함수)
const changeColorAction = (color) => {
// 주문서(action)를 생성
return {
type: 'CHANGE_COLOR',
color: color,
timestamp: new Date().toISOString()
}
}
const renderRedComponent = () => {
const state = store.getState()
document.getElementById('red-component').innerHTML = `
<div class="container" id="component_red" style="background-color: ${state.color}">
<h1>Red Component</h1>
<input type="button" value="Red!" onclick="
handleColorChange('red');
">
</div>
`
}
const renderGreenComponent = () => {
const state = store.getState()
document.getElementById('green-component').innerHTML = `
<div class="container" id="component_green" style="background-color: ${state.color}">
<h1>Green Component</h1>
<input type="button" value="Green!" onclick="
handleColorChange('green');
">
</div>
`
}
const renderBlueComponent = () => {
const state = store.getState()
document.getElementById('blue-component').innerHTML = `
<div class="container" id="component_blue" style="background-color: ${state.color}">
<h1>Blue Component</h1>
<input type="button" value="blue!" onclick="
handleColorChange('blue');
">
</div>
`
}
const renderTestComponent = () => {
const state = store.getState()
document.getElementById('test-component').innerHTML = `
<div class="container" id="component_test" style="background-color: ${state.color}">
<h1>Test Component</h1>
<input type="button" value="Test!" onclick="
handleColorChange('yellow');
">
</div>
`
}
const handleColorChange = (color) => {
// 주문서를 생성하고 커피숍에 전달
// store에 dispatch를 하게 되면 reducer가 호출됩니다.
// reducer는 현재 상태(state)와 주문서(action)를 받아 새로운 상태를 반환합니다.
store.dispatch(changeColorAction(color))
}
// 진동벨 받는 사람(고객)
store.subscribe(renderRedComponent)
store.subscribe(renderGreenComponent)
store.subscribe(renderBlueComponent)
// 초기 렌더링
renderRedComponent()
renderGreenComponent()
renderBlueComponent()
renderTestComponent() // 구독하지 않아 리렌더링되지 않는 컴포넌트
</script>
</body>
</html>
위 코드를 열어 Red! 버튼을 누르면 맨 위 세 컴포넌트는 모두 빨강이 되지만, 맨 아래 Test 컴포넌트는 노랑 그대로입니다. Test는 store.subscribe로 구독하지 않았기 때문입니다. 값을 바꾸면 store가 구독한 함수만 다시 호출하므로, 구독한 컴포넌트만 화면이 바뀝니다. Test의 Test! 버튼(yellow)을 눌러도 Test 자신은 이미 노랑이라 변화가 없고, 나머지 셋만 노랑으로 돌아옵니다. 구독해야 화면이 바뀐다는 점을 눈으로 확인해 두세요.
참고로 Redux.createStore는 redux 4.2부터 에디터에서 줄이 쳐지는(deprecated) 함수입니다. 동작은 그대로이고, 원리를 배우는 데 가장 간단해서 이 장에서는 계속 씁니다. 실무에서는 Redux Toolkit을 쓰며 10-5에서 바꿔 봅니다.
아래는 같은 코드에 AI가 주석을 달고 console.log를 넣은 버전입니다. 개발자 도구 콘솔을 열고 버튼을 누르면 reducer가 불리는 순서, 상태가 바뀌는 순서, 구독한 함수가 실행되는 순서가 한 줄씩 찍힙니다. 길어서 접어 두었습니다.
콘솔 로그가 찍히는 주석판 코드
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Modern Redux Color Changer</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/redux/4.0.1/redux.js"></script>
<style>
.container {
border: 5px solid black;
padding: 10px;
}
</style>
</head>
<body>
<div id="red-component"></div>
<div id="blue-component"></div>
<div id="green-component"></div>
<script>
/**
* =====================================================
* REDUX CORE: REDUCER 함수
* =====================================================
* Redux의 핵심 - 순수 함수로 상태 변화를 처리
*
* 핵심 원칙:
* 1. 순수 함수: 같은 입력에 대해 항상 같은 출력
* 2. 불변성: 기존 state를 직접 수정하지 않고 새로운 객체 반환
* 3. 부수 효과 없음: API 호출, DOM 조작 등 금지
*
* @param {Object} state - 현재 애플리케이션 상태
* @param {Object} action - 상태 변경 명령 객체 (type 필수)
* @returns {Object} 새로운 상태 객체
*/
const reducer = (state, action) => {
console.log('Reducer 호출:', {
currentState: state,
action: action,
timestamp: new Date().toLocaleTimeString(),
});
// 초기 상태 설정
// Redux store 생성 시 자동으로 호출되며, 이때 state는 undefined
if (state === undefined) {
const initialState = { color: 'yellow' };
console.log('초기 상태 설정:', initialState);
return initialState;
}
// Action 타입에 따른 상태 변경 처리
switch (action.type) {
case 'CHANGE_COLOR':
console.log('색상 변경:', `${state.color} → ${action.color}`);
// 불변성을 위해 spread operator 사용 (ES6+)
// Object.assign 대신 더 현대적인 방식
const newState = {
...state, // 기존 상태의 모든 속성 복사
color: action.color, // color 속성만 새 값으로 덮어쓰기
};
console.log('새로운 상태 생성:', newState);
return newState;
default:
// 알 수 없는 action type인 경우 기존 상태 그대로 반환
console.log('알 수 없는 액션 타입:', action.type);
return state;
}
};
/**
* =====================================================
* REDUX STORE 생성 및 설정
* =====================================================
* Redux store: 애플리케이션의 상태를 관리하는 중앙 저장소
*/
const store = Redux.createStore(
reducer,
// Redux DevTools Extension 연동 (브라우저 확장 프로그램)
// 개발 중에만 사용, 프로덕션에서는 제거 권장
window.__REDUX_DEVTOOLS_EXTENSION__ &&
window.__REDUX_DEVTOOLS_EXTENSION__(),
);
console.log('Redux Store 생성 완료');
console.log('초기 상태:', store.getState());
/**
* =====================================================
* UTILITY FUNCTIONS
* =====================================================
*/
/**
* 액션 생성자 함수 (Action Creator)
* 액션 객체 생성을 위한 팩토리 함수
* @param {string} color - 변경할 색상
* @returns {Object} Redux 액션 객체
*/
const changeColorAction = (color) => ({
type: 'CHANGE_COLOR',
color: color,
timestamp: Date.now(), // 추가 메타데이터
});
/**
* =====================================================
* COMPONENT FUNCTIONS (View Layer)
* =====================================================
* 각 컴포넌트는 자신만의 렌더링 로직을 가짐
* Redux 상태가 변경될 때마다 자동으로 리렌더링
*/
/**
* Red 컴포넌트 렌더링 함수
* store.subscribe()에 의해 상태 변경 시 자동 호출
*/
const renderRedComponent = () => {
console.log('Red 컴포넌트 렌더링 시작');
// 현재 상태를 store에서 가져오기
const currentState = store.getState();
// 대상 DOM 요소 찾기
const targetElement = document.querySelector('#red-component');
// HTML 템플릿 리터럴을 사용한 동적 렌더링
targetElement.innerHTML = `
<div class="container" style="background-color: ${currentState.color}">
<h1>red</h1>
<input type="button" value="fire" onclick="handleColorChange('red')">
</div>
`;
console.log('Red 컴포넌트 렌더링 완료');
};
/**
* Blue 컴포넌트 렌더링 함수
*/
const renderBlueComponent = () => {
console.log('Blue 컴포넌트 렌더링 시작');
const currentState = store.getState();
const targetElement = document.querySelector('#blue-component');
targetElement.innerHTML = `
<div class="container" style="background-color: ${currentState.color}">
<h1>blue</h1>
<input type="button" value="fire" onclick="handleColorChange('blue')">
</div>
`;
console.log('Blue 컴포넌트 렌더링 완료');
};
/**
* Green 컴포넌트 렌더링 함수
*/
const renderGreenComponent = () => {
console.log('Green 컴포넌트 렌더링 시작');
const currentState = store.getState();
const targetElement = document.querySelector('#green-component');
targetElement.innerHTML = `
<div class="container" style="background-color: ${currentState.color}">
<h1>green</h1>
<input type="button" value="fire" onclick="handleColorChange('green')">
</div>
`;
console.log('Green 컴포넌트 렌더링 완료');
};
/**
* =====================================================
* EVENT HANDLERS
* =====================================================
*/
/**
* 색상 변경 이벤트 핸들러
* 버튼 클릭 시 호출되어 Redux 액션을 디스패치
* @param {string} color - 변경할 색상
*/
const handleColorChange = (color) => {
console.log(`색상 변경 요청: ${color}`);
// 액션 생성자를 사용하여 액션 객체 생성
const action = changeColorAction(color);
// Redux store에 액션 디스패치
// 이로 인해 reducer가 호출되고, 상태가 변경되며, 구독자들이 실행됨
store.dispatch(action);
console.log('액션 디스패치 완료:', action);
};
/**
* =====================================================
* SUBSCRIPTION & INITIALIZATION
* =====================================================
* Redux store 구독 설정 및 초기 렌더링
*/
// 상태 변경 감지를 위한 구독자 등록
// store.subscribe()는 상태가 변경될 때마다 등록된 함수를 자동 실행
console.log('컴포넌트 구독자 등록 중...');
store.subscribe(renderRedComponent);
store.subscribe(renderBlueComponent);
store.subscribe(renderGreenComponent);
console.log('모든 구독자 등록 완료');
/**
* =====================================================
* INITIAL RENDER
* =====================================================
* 애플리케이션 시작 시 초기 렌더링 수행
*/
console.log('초기 렌더링 시작...');
// 각 컴포넌트 초기 렌더링
renderRedComponent();
renderBlueComponent();
renderGreenComponent();
console.log('애플리케이션 초기화 완료!');
/**
* =====================================================
* REDUX 동작 흐름 정리
* =====================================================
*
* 1. 사용자 인터랙션
* - 사용자가 버튼 클릭
* - handleColorChange() 함수 실행
*
* 2. 액션 생성 및 디스패치
* - changeColorAction()으로 액션 객체 생성
* - store.dispatch()로 Redux store에 액션 전달
*
* 3. Reducer 실행
* - Redux가 자동으로 reducer 함수 호출
* - 현재 상태(state)와 액션(action)을 매개변수로 전달
*
* 4. 상태 업데이트
* - reducer가 새로운 상태 객체 반환
* - Redux가 상태 변경을 감지
*
* 5. 구독자 실행
* - store.subscribe()로 등록된 모든 함수들이 자동 실행
* - 각 컴포넌트 렌더링 함수가 순차적으로 호출
*
* 6. UI 업데이트
* - store.getState()로 새로운 상태 조회
* - DOM 요소들이 새로운 상태에 맞게 업데이트
*
* (반복) 이 과정이 매번 반복되어 상태와 UI의 동기화 유지
*/
// 전역 함수로 등록 (onclick 핸들러에서 사용하기 위함)
window.handleColorChange = handleColorChange;
</script>
</body>
</html>
우리가 앞에서 배운 리액트에서 클릭 이벤트가 발생했을 때, 해당 값들은 Hook을 사용해서 값의 상태를 바꿔준 후 화면을 리렌더링하여 값들을 보여주었습니다. 즉, useState를 사용하여 리액트에게 값의 변경을 알리면 리액트가 UI를 업데이트하였습니다.
리덕스도 useState와 마찬가지로 변하는 값들을 관리해주는 관리 시스템입니다. 차이는 useState가 컴포넌트 단위로 상태를 관리했다면, 리덕스는 전역으로 데이터 상태를 관리합니다. 데이터들의 값이 바뀌었을 때 그 값들을 사용하는 모든 컴포넌트들에게 변경된 값을 전달해주고 그 값들을 다시 화면에 보여줍니다.
다음 내용을 살펴보기 전에 리덕스 데브툴스를 설치해 주세요. 그리고 생활코딩의 코드를 VSC의 Live Server로 켜놓고 해당 툴을 실행해 보세요. 상태를 다운로드 받아 다시 import하면 그 상태 그대로를 재생할 수 있습니다.
Redux DevTools
개발자 도구를 열어보면 요소, 콘솔, 소스 메뉴 옆으로 >>가 보이실 것입니다. 누르시면 Redux라는 메뉴를 보실 수 있습니다.
- 클릭한 이벤트를 표시합니다. 이를 통해 어떤 이벤트가 발생되었는지 디버깅이 가능합니다. 또한 이 이벤트를 jump나 skip할 수 있어요.
- 동영상 보듯이 play가 가능합니다. 이를 통해 어떠한 이벤트가 순차적으로 발생되었는지 확인할 수 있습니다.
- 이벤트들을 밖으로 내보내거나 가져올 수 있습니다.
마지막 수정