-
Redux를 사용했을 때의 데이터 흐름 Redux 구조
Action → Dispatch → Reducer → Store 순서로 데이터가 단방향
1. 상태가 변경되어야 하는 이벤트 발생시, 변경될 상태에 대한 정보가 담긴 Action 객체가 생성
2. 이 Action 객체는 Dispatch 함수의 인자로 전달
3. Dispatch 함수는 Action 객체를 Reducer 함수로 전달
4. Reducer 함수는 Action 객체의 값을 확인하고, 그 값에 따라 전역 상태 저장소 Store의 상태를 변경
5. 상태가 변경되면, React는 화면을 다시 렌더링
Store
➡️ 상태가 관리되는 오직 하나뿐인 저장소 역할
import { createStore } from 'redux'; const store = createStore(rootReducer);
Reducer
➡️ Reducer는 Dispatch에게서 전달받은 Action 객체의 type 값에 따라서 상태를 변경시키는 함수, Reducer는 순수함수여야함
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가 리턴하는 값이 새로운 상태가 됩니다.
Action
➡️ 어떤 액션을 취할 것인지 정의해 놓은 객체 (type은 필수 지정후 대문자와 Snake Casefh 작성하기. payload로 구체적인 값 전달)
// payload가 필요 없는 경우 const increase = () => { return { type: 'INCREASE' } } // payload가 필요한 경우 const setNumber = (num) => { return { type: 'SET_NUMBER', payload: num } }
Dispatch
➡️ Reducer로 Action을 전달해 주는 함수 (전달인자로 Action 객체 전달, Action 객체를 전달받은 함수는 Reducer 호출)
// Action 객체를 직접 작성하는 경우 dispatch( { type: 'INCREASE' } ); dispatch( { type: 'SET_NUMBER', payload: 5 } ); // 액션 생성자(Action Creator)를 사용하는 경우 dispatch( increase() ); dispatch( setNumber(5) );
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
useSelectior() : 컴포넌트와 state를 연결하여 Redux의 state에 접근할 수 있게 해주는 메서드
// Redux Hooks 메서드는 'redux'가 아니라 'react-redux'에서 불러옵니다. import { useSelector } from 'react-redux' const counter = useSelector(state => state) console.log(counter) // 1
Redux의 세 가지 원칙
1. Single source of truth : 동일한 데이터는 항상 같은 곳에서 가져와야하며 Store라는 하나뿐인 공간이 있으며 연결이 돼야 함
2. State is read-only : 읽기전용, 상태를 직접 변경할 수 없음. Action 객체가 있어야 상태를 변경할 수 있음
3. Changes are made with pure functions : 변경은 순수함수로만 가능
'FE' 카테고리의 다른 글
웹표준 (0) 2023.06.26 Cmarket Redux (0) 2023.06.23 [React] 상태관리 (0) 2023.06.21 React Custom Component (0) 2023.06.20 useRef (0) 2023.06.19