[State Managemen]Redux
Redux의 상태관리
- 상태가 변경 이벤트가 발생, 변경될 상태에 대한 정보가 담긴 Action 객체가 생성
- Action 객체는 Dispatch 함수의 인자로 전달
- Dispatch 함수는 Action 객체를 Reducer 함수로 전달
- Reducer 함수는 Action 객체 값 확인, 그 값에 따라 전역 상태 저장소 Store의 상태를 변경
- 상태가 변경되면, React는 화면 리렌더링 합니다.

Action → Dispatch → Reducer → Store
store
store 생성
import { createStore } from "redux";
const store = createStore(rootReducer);
Reducer
Reducer는 Dispatch에게서 전달받은 Action 객체의 type 값에 따라서 상태를 변경시키는 함수
const count = 1;
// Reducer를 생성할 때에는 초기 상태를 인자로 요구합니다.
const counterReducer = (state = count, action) => {
// Action 객체의 type 값에 따라 분기하는 switch 조건문입니다.
switch (action.type) {
//action === 'INCREASE'일 경우
case "INCREASE":
return state + 1;
// action === 'DECREASE'일 경우
case "DECREASE":
return state - 1;
// action === 'SET_NUMBER'일 경우
case "SET_NUMBER":
return action.payload;
// 해당 되는 경우가 없을 땐 기존 상태를 그대로 리턴
default:
return state;
}
};
// Reducer가 리턴하는 값이 새로운 상태가 됩니다.
Reducer함수 첫번째 인자에는 기존 state.
첫번째 인자에는 default value 설정, 그렇지 않을 경우 undefined가 할당, 오류 발생
여러 개의 Reducer를 Redux의 combineReducers메서드로 하나의 Reducer로 합칠 수 있다.
import { combineReducers } from 'redux';
const rootReducer = combineReducers({
counterReducer,
anyReducer,
...
});
Redux의 state 업데이트는 immutable한 방식으로 변경해야 한다 - 변경된 state를 로그로 남기기 위해서
action
어떤 액션을 취할 것인지 정의해 놓은 객체
// payload가 필요 없는 경우
{ type: 'INCREASE' }
// payload가 필요한 경우
{ type: 'SET_NUMBER', payload: 5 }
type 은 필수로 지정, Action객체가 어떤 동작을 하는지 명시해주는 역할, 대문자와 Snake Case로 작성, 필요에 따라 payload 를 작성해 구체적인 값을 전달
Action 객체를 생성하는 함수를 만들어 사용 - 액션 생성자(Action Creator)
// payload가 필요 없는 경우
const increase = () => {
return {
type: "INCREASE",
};
};
// payload가 필요한 경우
const setNumber = (num) => {
return {
type: "SET_NUMBER",
payload: num,
};
};
Action 객체는 Dispatch 함수를 통해 Reducer 함수 두번째 인자로 전달
dispatch
Reducer로 Action을 전달해주는 함수, 전달인자로 Action 객체가 전달
// Action 객체를 직접 작성하는 경우
dispatch({ type: "INCREASE" });
dispatch({ type: "SET_NUMBER", payload: 5 });
// 액션 생성자(Action Creator)를 사용하는 경우
dispatch(increase());
dispatch(setNumber(5));
Action 객체를 전달받은 Dispatch 함수는 Reducer를 호출
Redux Hooks
주요한 훅 메서드 useSelector(), useDispatch()
useDispatch()
Action 객체를 Reducer로 전달해 주는 Dispatch 함수를 반환하는 메서드.
import { useDispatch } from "react-redux";
const dispatch = useDispatch();
dispatch(increase());
console.log(counter); // 2
dispatch(setNumber(5));
console.log(counter); // 5
useSelector()
컴포넌트와 state를 연결하여 Redux의 state에 접근할 수 있게 해주는 메서드
import { useSelector } from "react-redux";
const counter = useSelector((state) => state);
console.log(counter); // 1
Redux의 세 가지 원칙
-
Single source of truth
동일한 데이터는 항상 같은 곳에서 가지고 와야 한다는 의미. 데이터를 저장하는 Store라는 단 하나뿐인 공간이 있음
-
State is read-only
상태는 읽기 전용, Redux의 상태도 직접 변경할 수 없음. 즉, Action 객체가 있어야만 상태를 변경할 수 있음
-
Changes are made with pure functions
변경은 순수함수로만 가능, 순수함수로 작성되어야하는 Reducer와 연결되는 원칙입니다.
// 방법1
export const reducer = (initialState, action) => {
if (typeof initialState === _________) {
initialState = 1;
}
...
};
// 방법2
export const reducer = (initialState = 1, action) => {
...
};
리듀서가 처음 호출될 때, state값은 undefined, 따라서 state의 초깃값을 지정해서 액션이 발생하기 전에 이 케이스에 대해 처리.
댓글남기기