action
이라는 이벤트를 사용해서 애플리케이션의 상태를 관리하고 업데이트하는 라이브러리store
에 저장하고, 이러한 state는 예측가능한 방식으로만 업데이트 됨⚠️ React 없이도 사용할 수 있는 상태 관리 라이브러리임
Redux | React |
---|---|
컴포넌트와 상태를 분리하는 패턴 | 상태와 속성(props)을 이용한 컴포넌트 단위 개발 아키텍처 |
즉, Redux에서는 데이터가 단방향으로 흐르며, 그 순서는 Action → Dispatch → Reducer → Store
createStore
메서드를 활용해 Reducer
를 연결해서 Store
를 생성
⚠️ 반드시 Reducer
와 연결해야함
import { createStore } from 'redux';
const store = createStore(rootReducer);
Dispatch
에게서 전달받은 Action
객체의 type
값에 따라서 상태를 변경시키는 함수Reducer
는 순수함수현재 state
와 action
을 전달인자로 받아 새로운 state
를 리턴함(state, action) => newState
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가 리턴하는 값이 새로운 상태가 됩니다.
combineReducers
메서드를 사용해서 하나의 Reducer로 합치기import { combineReducers } from 'redux';
const rootReducer = combineReducers({
counterReducer,
anyReducer,
...
});
어떤 액션을 취할 것인지 정의해 놓은 객체
type
payload
보통 Action 객체를 생성하는 함수를 만들어 사용
// payload가 필요 없는 경우
const increase = () => {
return {
type: 'INCREASE'
}
}
// payload가 필요한 경우
const setNumber = (num) => {
return {
type: 'SET_NUMBER',
payload: num
}
}
// Action 객체를 직접 작성하는 경우
dispatch( { type: 'INCREASE' } );
dispatch( { type: 'SET_NUMBER', payload: 5 } );
// 액션 생성자(Action Creator)를 사용하는 경우
dispatch( increase() );
dispatch( setNumber(5) );
Dispatch 함수를 반환하는 메서드
import { useDispatch } from 'react-redux'
const dispatch = useDispatch()
dispatch( increase() )
console.log(counter) // 2
dispatch( setNumber(5) )
console.log(counter) // 5
컴포넌트와 state를 연결하여 Redux의 state에 접근할 수 있게 해주는 메서드
import { useSelector } from 'react-redux'
const counter = useSelector(state => state)
console.log(counter) // 1
참고자료
ko.redux.js.org