바닐라JS에서 Redux 실습
1. 바닐라JS에서 직접 만들어보기
1.1 Redux 설치하기
이 절의 예제도 10-1처럼 HTML 파일 하나에 CDN으로 redux를 불러와 실습합니다. 아래 주소를 <head> 안에 넣으세요. 최신 5.x는 <script>로 불러도 전역 Redux가 생기지 않아서 4.x 주소를 씁니다.
<script src="https://cdnjs.cloudflare.com/ajax/libs/redux/4.0.1/redux.js"></script>
1.2 요구사항
Google Fonts 사이트와 같은 사이트를 만들 것입니다. 여기서 sentence에 text를 입력하면 모든 font box에 반영이 됩니다. 이 기능을 구현해보도록 하겠습니다.
Google Fonts
최종 화면은 아래와 같습니다.
- 텍스트 입력 칸과 버튼(아래 정답 코드에서는 "눌러버렷!") : 입력한 텍스트를 모든 박스에 반영
- Rounded, Circle, Rect : 모든 박스에 각각 border-radius 10px, 20px, 0px 반영
- Red, Green, Blue : 모든 박스에 Border color 변경

그림은 버튼을 누르기 전의 처음 상태입니다. 입력 칸에 글자를 쓰고 버튼을 누르면 여섯 칸의 글자가 모두 바뀌고, Rounded!나 Circle!을 누르면 여섯 칸의 모서리가 모두 둥글어지고, Red!를 누르면 여섯 칸의 테두리가 모두 빨강이 됩니다. 이 "모두"가 Redux를 쓰는 이유입니다. 버튼은 요청 하나만 보내고, 여섯 칸이 각자 store에서 값을 읽어 자기를 고칩니다.
1.3 정답 코드
Google Fonts 클론 정답 코드 (꼭 다 푸신 다음 확인하세요)
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/redux/4.0.1/redux.js"></script>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link
href="https://fonts.googleapis.com/css2?family=Anek+Malayalam:wght@300&family=Fascinate&family=Kdam+Thmor+Pro&family=Noto+Sans+KR:wght@300&family=Open+Sans&family=Roboto:wght@300&display=swap"
rel="stylesheet">
<style>
.container {
border: 5px solid black;
padding: 10px;
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 10px;
}
.item {
border: 5px solid #f6866a;
height: 100px;
padding: 20px;
font-size: 32px;
}
.item:nth-child(1) {
font-family: 'Anek Malayalam', sans-serif;
}
.item:nth-child(2) {
font-family: 'Fascinate', cursive;
}
.item:nth-child(3) {
font-family: 'Kdam Thmor Pro', sans-serif;
}
.item:nth-child(4) {
font-family: 'Noto Sans KR', sans-serif;
}
.item:nth-child(5) {
font-family: 'Open Sans', sans-serif;
}
.item:nth-child(6) {
font-family: 'Roboto', sans-serif;
}
</style>
</head>
<body>
<input type="text" id="inputText">
<input type="button" value="눌러버렷!" onclick="
const value = document.getElementById('inputText').value
store.dispatch({type:'TEXT', text:value})
" />
<input type="button" value="Rounded!" onclick="
store.dispatch({type:'STYLE_BORDER', borderRadius:'10px'})
" />
<input type="button" value="Circle!" onclick="
store.dispatch({type:'STYLE_BORDER', borderRadius:'20px'})
" />
<input type="button" value="Rect!" onclick="
store.dispatch({type:'STYLE_BORDER', borderRadius:'0px'})
" />
<input type="button" value="Red!" onclick="
store.dispatch({type:'STYLE_BORDER_COLOR', border:'5px solid red'})
" />
<input type="button" value="Green!" onclick="
store.dispatch({type:'STYLE_BORDER_COLOR', border:'5px solid green'})
" />
<input type="button" value="Blue!" onclick="
store.dispatch({type:'STYLE_BORDER_COLOR', border:'5px solid blue'})
" />
<br>
<br>
<div class="container">
<div id="item1" class="item"></div>
<div id="item2" class="item"></div>
<div id="item3" class="item"></div>
<div id="item4" class="item"></div>
<div id="item5" class="item"></div>
<div id="item6" class="item"></div>
</div>
<script>
const store = Redux.createStore(reducer)
function reducer(state, action) {
console.log(state, action)
if (state === undefined) {
return {
text: 'hello',
color: 'black',
border: '5px solid #f6866a',
borderRadius: '0px'
}
} else if (action.type === 'TEXT') {
return {
...state,
text: action.text
}
} else if (action.type === 'STYLE_BORDER') {
return {
...state,
borderRadius: action.borderRadius
}
} else if (action.type === 'STYLE_BORDER_COLOR') {
return {
...state,
border: action.border
}
}
return state
}
function item1() {
const state = store.getState()
const $item = document.querySelector('#item1')
$item.innerText = `${state.text}`
$item.style.borderRadius = `${state.borderRadius}`
$item.style.border = `${state.border}`
}
store.subscribe(item1)
item1()
function item2() {
const state = store.getState()
const $item = document.querySelector('#item2')
$item.innerText = `${state.text}`
$item.style.borderRadius = `${state.borderRadius}`
$item.style.border = `${state.border}`
}
store.subscribe(item2)
item2()
function item3() {
const state = store.getState()
const $item = document.querySelector('#item3')
$item.innerText = `${state.text}`
$item.style.borderRadius = `${state.borderRadius}`
$item.style.border = `${state.border}`
}
store.subscribe(item3)
item3()
function item4() {
const state = store.getState()
const $item = document.querySelector('#item4')
$item.innerText = `${state.text}`
$item.style.borderRadius = `${state.borderRadius}`
$item.style.border = `${state.border}`
}
store.subscribe(item4)
item4()
function item5() {
const state = store.getState()
const $item = document.querySelector('#item5')
$item.innerText = `${state.text}`
$item.style.borderRadius = `${state.borderRadius}`
$item.style.border = `${state.border}`
}
store.subscribe(item5)
item5()
function item6() {
const state = store.getState()
const $item = document.querySelector('#item6')
$item.innerText = `${state.text}`
$item.style.borderRadius = `${state.borderRadius}`
$item.style.border = `${state.border}`
}
store.subscribe(item6)
item6()
</script>
</body>
</html>
정답의 item1()부터 item6()까지는 같은 모양이 여섯 번 반복됩니다. 영상 예제를 그대로 옮긴 것이고, 칸마다 함수를 하나씩 두고 각각 store.subscribe로 구독한다는 점을 눈에 익히기 위한 모양입니다. 익숙해지면 칸 여섯 개를 한 함수가 돌며 그리게 하고 subscribe도 한 번만 해도 같은 화면이 됩니다. 한 가지 더, 이 reducer는 마지막에 return state를 둡니다. 알 수 없는 action이 오면 state를 그대로 돌려줘야 undefined가 되지 않습니다(10-2의 default와 같은 역할).
1.4 추가 문제
Airbnb와 비슷한 서비스를 만들어보도록 하겠습니다. 오른쪽에 있는 지도는 구현할 필요가 없고, 위 Google fonts 서비스를 참고하여 ‘무료 주차 공간, 대형 욕조, 바비큐 그릴, 게스트용 별채, 수영장, 주방, TV’에 따라 각 방들의 테두리가 변하게, 또는 나타나게 해주세요.
일반 JavaScript의 filter를 사용한 것과 어떤 차이가 있는지도 비교해보세요. 정답 코드 아래에 그 비교를 정리해 두었습니다.
- 가능하면 위 Google Fonts 정답을 보면서 직접 짜보려 해보세요.
- 어려우시면 LLM에게 힌트 정도를 구해보세요.
- 그래도 못 풀겠다면 LLM에게 문제 전체를 Google Fonts 코드와 함께 올려 코드를 받으세요. 코드를 받았다면 사람이 할 일은 그다음입니다. 직접 열어서 수영장을 누르고, 이어서 TV를 눌러 보세요. 필터는 겹쳐서 적용되므로 수영장과 TV를 모두 가진 숙소만 남습니다. 활성 필터와 결과 숫자가 요구한 대로 바뀌는지 확인하고, 아래 정답 코드와 비교해 어디가 다른지 따져 보세요. 받은 코드가 요구와 다르게 동작하면 무엇이 다른지 적어 다시 요청하면 됩니다.

Airbnb 필터링 정답 코드
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/redux/4.0.1/redux.js"></script>
<style>
body {
font-family: Arial, sans-serif;
padding: 20px;
}
.filter-btn {
padding: 8px 16px;
margin: 5px;
border: 2px solid #ddd;
background: white;
cursor: pointer;
}
.filter-btn.active {
background: #ff5a5f;
color: white;
}
.listing {
border: 3px solid #ddd;
padding: 15px;
margin: 10px 0;
}
.listing.hidden {
display: none;
}
.amenity {
display: inline-block;
background: #f0f0f0;
padding: 2px 6px;
margin: 2px;
font-size: 12px;
}
.amenity.highlight {
background: #ff5a5f;
color: white;
}
</style>
</head>
<body>
<h1>Redux Airbnb 필터링</h1>
<div>
<h3>편의시설 필터:</h3>
<button class="filter-btn" onclick="toggleFilter('무료 주차 공간')">무료 주차 공간</button>
<button class="filter-btn" onclick="toggleFilter('대형 욕조')">대형 욕조</button>
<button class="filter-btn" onclick="toggleFilter('바비큐 그릴')">바비큐 그릴</button>
<button class="filter-btn" onclick="toggleFilter('게스트용 별채')">게스트용 별채</button>
<button class="filter-btn" onclick="toggleFilter('수영장')">수영장</button>
<button class="filter-btn" onclick="toggleFilter('주방')">주방</button>
<button class="filter-btn" onclick="toggleFilter('TV')">TV</button>
</div>
<div id="resultsInfo"></div>
<div id="listingsContainer">
<!-- 숙소 목록이 여기에 렌더링 -->
</div>
<script>
// 샘플 데이터
const listings = [
{ id: 1, title: "도심 아파트", location: "강남구", price: "85,000원", amenities: ["무료 주차 공간", "주방", "TV"] },
{ id: 2, title: "럭셔리 펜트하우스", location: "한남동", price: "250,000원", amenities: ["대형 욕조", "수영장", "게스트용 별채", "주방", "TV"] },
{ id: 3, title: "바다뷰 펜션", location: "해운대", price: "120,000원", amenities: ["바비큐 그릴", "주방", "무료 주차 공간"] },
{ id: 4, title: "산속 별장", location: "평창", price: "95,000원", amenities: ["바비큐 그릴", "게스트용 별채", "무료 주차 공간", "TV"] },
{ id: 5, title: "모던 스튜디오", location: "홍대", price: "65,000원", amenities: ["주방", "TV"] },
{ id: 6, title: "리조트 빌라", location: "제주도", price: "180,000원", amenities: ["수영장", "대형 욕조", "바비큐 그릴", "무료 주차 공간", "주방", "TV"] }
];
// Redux 스토어 생성
const store = Redux.createStore(reducer);
function reducer(state, action) {
console.log('Redux Action:', action); // Redux 액션 로깅
if (state === undefined) {
return {
listings: listings,
activeFilters: [],
filteredListings: listings
};
}
if (action.type === 'TOGGLE_FILTER') {
const newFilters = state.activeFilters.includes(action.filter)
? state.activeFilters.filter(f => f !== action.filter)
: [...state.activeFilters, action.filter];
const filteredListings = newFilters.length === 0
? state.listings
: state.listings.filter(listing =>
newFilters.every(filter => listing.amenities.includes(filter))
);
return {
...state,
activeFilters: newFilters,
filteredListings: filteredListings
};
}
return state;
}
// 액션 디스패치
function toggleFilter(filter) {
store.dispatch({ type: 'TOGGLE_FILTER', filter: filter });
}
// UI 업데이트 함수들
function updateUI() {
const state = store.getState();
console.log('Current State:', state); // 현재 상태 로깅
// 필터 버튼 업데이트
document.querySelectorAll('.filter-btn').forEach(btn => {
const filterText = btn.textContent.trim();
btn.classList.toggle('active', state.activeFilters.includes(filterText));
});
// 결과 정보 업데이트
const resultsInfo = document.getElementById('resultsInfo');
resultsInfo.innerHTML = `<p><strong>활성 필터:</strong> ${state.activeFilters.join(', ') || '없음'} | <strong>결과:</strong> ${state.filteredListings.length}개 숙소</p>`;
// 숙소 목록 업데이트
const container = document.getElementById('listingsContainer');
container.innerHTML = state.filteredListings.map(listing => `
<div class="listing">
<h4>${listing.title} - ${listing.location}</h4>
<p>가격: ${listing.price}</p>
<p>편의시설:
${listing.amenities.map(amenity =>
`<span class="amenity ${state.activeFilters.includes(amenity) ? 'highlight' : ''}">${amenity}</span>`
).join(' ')}
</p>
</div>
`).join('');
}
// 스토어 구독 - 상태가 변경될 때마다 UI 업데이트
store.subscribe(updateUI);
// 초기 렌더링
updateUI();
</script>
</body>
</html>
같은 기능에서 필터를 바꾸는 부분만 Redux 없이 일반 JavaScript로 쓰면 이 정도입니다. updateUI는 이 activeFilters 배열을 읽어 숙소를 걸러서 그리게 됩니다.
let activeFilters = [];
function toggleFilter(filter) {
if (activeFilters.includes(filter)) {
activeFilters = activeFilters.filter((f) => f !== filter);
} else {
activeFilters.push(filter);
}
updateUI();
}
이 예제가 과한 설계가 아니냐고 Claude에게 물었을 때의 답도 같았습니다. 이 예제에서는 이쪽이 더 짧고 읽기 쉽습니다. 값을 쓰는 곳이 updateUI 하나뿐이고 값을 고치는 곳도 toggleFilter 하나뿐이라, Redux가 해 주는 일(값을 한곳에 모으고 고치는 길을 하나로 정하는 일)이 아직 필요 없기 때문입니다. 정답 코드 하나만 더 짚으면, filteredListings는 listings와 activeFilters로 언제든 계산할 수 있는 값인데 state에 따로 저장하고 있습니다. 이런 값은 state에 넣으면 고칠 곳이 두 군데가 되므로 updateUI에서 계산하는 편이 안전합니다. 실습으로는 괜찮지만 알아 두세요.
Redux가 필요한 때와 필요 없는 때
- 필요 없는 때: 단순한 필터링·검색처럼 컴포넌트 한두 개가 쓰는 값, 상태가 단순한 개인 프로젝트나 프로토타입.
- 필요한 때: 여러 화면이 같은 값(로그인 정보, 장바구니 개수 등)을 읽고 쓰는 경우. 액션 하나가 여러 값을 한꺼번에 바꾸는 경우(구매하면 재고가 줄고, 장바구니가 비고, 주문 내역과 포인트가 늘어나는 것처럼). 버그가 났을 때 "값이 어떤 순서로 바뀌었는지"를 추적해야 하는 경우(10-1의 Redux DevTools가 이 기록을 보여 줍니다).
값이 바뀐 순서를 추적한다는 말은 이런 장면입니다. 일반 방식에서는 값이 어디서 지워졌는지 코드를 뒤져야 하고, Redux에서는 액션 기록(DevTools를 연결했을 때)에 남습니다.
// 일반 방식: 누가 언제 지웠는지 알 수 없습니다
activeFilters.push('수영장');
// ... 코드 100줄 뒤
activeFilters = []; // 누가 언제 이걸 했지?
// Redux 방식: 변화가 액션으로 기록됩니다
// 1. { type: 'ADD_FILTER', filter: '수영장' }
// 2. { type: 'CLEAR_FILTERS' }
필터가 하나뿐인 이 예제는 학습용이라 Redux를 썼지만 실제로는 일반 filter가 더 알맞습니다. 무엇을 전역 상태에 넣을지, 그리고 Redux까지 필요한지는 사람이 정하는 일입니다.
마지막 수정