1.상태 변경 이벤트 발생하면, 변경될 상태에 대한 정보가 담긴 Action 객체 생성
2. Action 객체 Dispatch 함수의 인자로 전달
3. Dispatch 함수는 Action 객체를 Reducer 함수로 전달
4. Reducer 함수는 Action 객체의 값을 확인하고, 그 값에 따라 전역 상태 저장소 Store의 상태를 변경
5. 상태가 변경되면, React는 화면을 다시 렌더링
상태변경요청 → Action(상태정보담김) → Dispatch(Reducer에 전달) → Reducer(store의 상태변경) → Store 순서로 데이터가 단방향 흐름
Store는 상태가 관리되는 오직 하나뿐인 저장소의 역할
createStore
메서드를 활용해 Reducer를 연결해서 Store를 생성
import { createStore } from 'redux';
const store = createStore(rootReducer);
Reducer는 Dispatch에게서 전달받은 Action 객체의 type 값에 따라서 상태를 변경시키는 함수(마치 useState의 함수처럼)
const count = 1
// Reducer를 생성할 때에는 초기 상태를 인자로 요구합니다.
const counterReducer = (state = count, action) => {
// 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는 순수함수여야 한다. 외부 요인으로 인해 변경되는 일 방지하기 위함이다.
여러 개의 Reducer를 사용하는 경우, Redux의 combineReducers 메서드를 사용해서 하나의 Reducer로 합쳐줄 수 있다.
import { combineReducers } from 'redux';
const rootReducer = combineReducers({
counterReducer,
anyReducer,
...
});
어떤 액션을 취할 것인지 정의해 놓은 객체
type은 필수로 지정을 해 주어야 한다. 해당 Action 객체가 어떤 동작을 하는지 명시해주는 역할을 하기 때문이다. 필요에 따라 payload 를 작성해 구체적인 값을 전달하기도 한다.
대문자와 Snake Case로 작성한다.
보통 Action을 직접 작성하기보다는 Action 객체를 생성하는 함수를 만들어 사용하는 경우가 많다. 이러한 함수를 액션 생성자(Action Creator)라고 한다.
// payload가 필요 없는 경우
// increase함수 실행 시 type: 'INCREASE' 인 Action객체 반환
const increase = () => {
return {
type: 'INCREASE'
}
}
// payload가 필요한 경우
const setNumber = (num) => {
return {
type: 'SET_NUMBER',
payload: num
}
}
Dispatch는 Reducer로 Action을 전달해주는 함수
Dispatch의 전달인자로 Action 객체가 전달된다.
Action 객체를 전달받은 Dispatch 함수는 Reducer를 호출한다.
// Action 객체를 직접 작성하는 경우
// Reducer에게 { type: 'INCREASE' }을 전달
dispatch( { type: 'INCREASE' } );
// Reducer에게 { type: 'SET_NUMBER', payload: 5 }을 전달
dispatch( { type: 'SET_NUMBER', payload: 5 } );
// 액션 생성자(Action Creator)를 사용하는 경우
// Reducer에게 increase()을 전달
dispatch( increase() );
// Reducer에게 setNumber(5)을 전달
dispatch( setNumber(5) );
useDispatch() 는 Action 객체를 Reducer로 전달해 주는 Dispatch 함수를 반환하는 메서드
import { useDispatch } from 'react-redux'
const dispatch = useDispatch()
import { useSelector } from 'react-redux'
// counter 변수 안에 state을 담아줘서 state 사용하고 싶을 때 counter로 작성
const counter = useSelector(state => state)
console.log(counter) // 1