Redux
- 가장 많이 사용하는 리액트 상태 관리 라이브러리
- 컴포넌트의 상태 업데이트 관련 로직을 다른 파일로 분리시켜 더욱 효율적으로 관리할 수 있음
- 컴포넌트끼리 똑같은 상태를 공유해야 할 때도 여러 컴포넌트를 거치지 않고 손쉽게 상태 값을 전달하거나 업데이트할 수 있음
- 전역 상태를 관리할 때 효과적
- 단순히 전역 상태 관리만 한다면 Context API를 사용하는 것으로 충분함
- 리덕스를 사용하면 상태를 더욱 체계적으로 관리할 수 있어서 프로젝트의 규모가 큰 경우 리덕스를 사용
- 코드 유지 보수성을 높여줌
- 작업 효율 극대화
- 미들웨어라는 기능을 제공해 비동기 작업을 훨씬 효율적으로 관리할 수 있게 해줌
액션
상태에 어떤 변화가 필요하면 액션(action)이란 것이 발생
{
type: "ADD_TODO",
data: {
id: 1,
text: '리덕스 배우기'
}
}
{
type: "CHANGE_INPUT",
text: "안녕하세요"
}
- 액션 객체는 type 필드를 반드시 가지고 있어야 한다
- 이 값을 액션의 이름이라고 생각하면 됨
- 이 외의 값들은 나중에 상태 업데이트를 할 때 참고해야할 값
액션 생성 함수 (action creator)
- 액션 객체를 만들어 주는 함수
- 어떤 변화를 일으켜야 할 때마다 액션 객체를 만들어야 하는데 매번 액션 객체를 직접 작성하기 번거롭고 정보를 놓칠 수도 있어서 함수로 만들어 관리
function addTodo(data) {
return {
type: "ADD_TODO",
data
};
}
// 화살표 함수로 만드는 경우
const changeInput = text => ({
type: "CHANGE_INPUT",
text
});
리듀서(reducer)
- 변화를 일으키는 함수
- 액션을 만들어서 발생시키면 리듀서가 현재 상태와 전달받은 액션 객체를 파라미터로 받아옴
- 두 값을 참고하여 새로운 상태를 만들어 반환
const initialState = {
counter: 1
};
function reducer(state = initialState, action) {
switch (action.type) {
case INCREMENT:
return {
counter: state.counter + 1
};
default :
return state;
}
}
스토어(store)
- 프로젝트에 리덕스를 적용하기 위해 스토어(store)를 만듦
- 한 개의 프로젝트는 단 하나의 스토어만 가질 수 있음
- 스토어 안에는 현재 애플리케이션 상태와 리듀서가 들어가 있으며, 그 외에도 몇가지 중요한 내장 함수를 지님
디스패치(dispatch)
- 스토어의 내장 함수 중 하나
- '액션을 발생시키는 것'이라고 이해하면 됨
- dispatch(action)과 같은 형태로 액션 객체를 파라미터로 넣어서 호출
- 이 함수가 호출되면 스토어는 리듀서 함수를 실행시켜서 새로운 상태를 만들어줌
구독 (subscribe)
- 스토어의 내장 함수 중 하나
- subscribe 함수 안에 리스너 함수를 파라미터로 넣어서 호출하면, 이 리스너 함수가 액션이 디스패치되어 상태가 업데이트될 때마다 호출됨
const listener = () => {
console.log("상태가 업데이트됨");
}
const unsubscribe = store.subscribe(listner);
unsubscribe(); // 추후 구독을 비활성화할 때 함수를 호출
리덕스 규칙
1. 단일 스토어
- 하나의 애플리케이션 안에는 하나의 스토어가 들어있음
- 여러개의 스토어를 사용하는게 불가능하지는 않지만 권장하지 않음
2. 읽기 전용 상태
- 리덕스 상태는 읽기 전용임
- 즉, 상태를 업데이트할 때 기존의 객체는 건드리지 않고 새로운 객체를 생성해주어야함
- 불변성을 유지해야 하는 이유는 내부적으로 데이터가 변경되는 것을 감지하기 위해 얕은 비교 검사를 하기 때문
3. 리듀서는 순수한 함수
- 변화를 일으키는 리듀서 함수는 순수한 함수여야 함
- 순수한 함수 조건
- 리듀서 함수는 이전 상태와 액션 객체를 파라미터로 받는다
- 파라미터 외의 값에는 의존하면 안됨
- 이전 상태는 절대 건드리지 않고, 변화를 준 새로운 상태 객체를 만들어 반환함
- 똑같은 파라미터로 호출된 리듀서 함수는 언제나 똑같은 결과 값을 반환함
- 순수한 함수 조건
더보기
바닐라 자바스크립트 환경에서 사용하는 리덕스
<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="./index.css" type="text/css" />
<title>Vanilla Redux</title>
</head>
<body>
<h1>0</h1>
<button id="increase">+1</button>
<button id="decrease">-1</button>
<script src="counter.js"></script>
</body>
</html>
// index.js
const counter = document.querySelector("h1")
const btnIncrease = document.querySelector("#increase")
const btnDecrease = document.querySelector("#decrease")
const initalState = {
counter: 0,
}
const INCREASE = "INCREASE"
const DECREASE = "DECREASE"
const increase = () => ({ type: INCREASE })
const decrease = () => ({ type: DECREASE })
const reducer = (state = initalState, action) => {
switch (action.type) {
case INCREASE:
return {
...state,
counter: state.counter + 1,
}
case DECREASE:
return {
...state,
counter: state.counter - 1,
}
default:
return state
}
}
import { createStore } from "redux"
const store = createStore(reducer)
const updateCounter = () => {
const state = store.getState()
counter.innerText = state.counter
}
store.subscribe(updateCounter)
//dispatch
btnIncrease.onclick = () => {
store.dispatch(increase(1))
}
btnDecrease.onclick = () => {
store.dispatch(decrease(0))
}
[Redux 흐름]
1. DOM을 만든다
const counter = document.querySelector("h1")
const btnIncrease = document.querySelector("#increase")
const btnDecrease = document.querySelector("#decrease")
2. 초기 값 설정 및 Actions 설정
const initalState = {
counter: 0,
}
const INCREASE = "INCREASE"
const DECREASE = "DECREASE"
const increase = () => ({ type: INCREASE })
const decrease = () => ({ type: DECREASE })
3. REDUCER를 만든다.
const reducer = (state = initalState, action) => {
switch (action.type) {
case INCREASE:
return {
...state,
counter: state.counter + 1,
}
case DECREASE:
return {
...state,
counter: state.counter - 1,
}
default:
return state
}
}
4. 스토어를 만든다
import { createStore } from "redux"
const store = createStore(reducer)
5. 구독(subscribe)을 만든다
const updateCounter = () => {
const state = store.getState()
counter.innerText = state.counter
}
store.subscribe(updateCounter)
6. dispatch를 한다 (실행시킨다)
btnIncrease.onclick = () => {
store.dispatch(increase(1))
}
btnDecrease.onclick = () => {
store.dispatch(decrease(0))
}
'React' 카테고리의 다른 글
[React] 리덕스 미들웨어를 통한 비동기 작업 관리 (0) | 2023.04.14 |
---|---|
[React] 리덕스를 사용해 상태 관리 (0) | 2023.04.06 |
[React] Context API (0) | 2023.04.05 |
[React] 라우팅 (0) | 2023.03.30 |
[React] immer를 사용해 불변성 유지 (0) | 2023.03.29 |