CodeStates/React
Section3 / Unit 4 : Redux
yeeendy
2023. 6. 22. 09:47
Redux
리액트의 상태 관리 라이브러리
state = 사용자 지정 변수
리덕스 = state를 한 곳에다 저장
저장할 때 store 단위로 저장, state의 저장과 조작을 다룬다
-> 사용하기 편리하며 오류를 잘 잡아줄 수 있다.
Redux 쓰는 이유
- props 문법 귀찮을 때
- state 변경 관리할 때
Redux 구조
- 상태가 변경되어야 하는 이벤트가 발생 → 변경될 상태에 대한 정보가 담긴 Action 객체가 생성
- 이 Action 객체는 Dispatch 함수의 인자로 전달
- Dispatch 함수는 Action 객체를 Reducer 함수로 전달
- Reducer 함수는 Action 객체의 값을 확인 → 전역 상태 저장소 Store의 상태를 변경
- 상태가 변경되면, React는 화면을 다시 렌더링
단방향 흐름
Action → Dispatch → Reducer → Store
( 함수 → 객체 → 함수 → 저장소 )
FLUX 패턴
단방향 데이터 흐름은 Flux 패턴의 중심이며 위의 다이어그램은 flux 프로그래머의 기본 정신 모델이어야 한다.
store
상태가 관리되는 오직 하나뿐인 저장소
Redux앱의 state가 저장되어 있는 공간
//Reducer를 연결해서 Store를 생성하는 방법
import { createStore } from 'redux';
const store = createStore(rootReducer);
reducer
→ dispatch에게서 전달받은 Action 객체의 type 값에 따라서 상태를 변경시키는 함수
→ 순수함수여야 함
여러 개의 Reducer를 사용하는 경우
→ combineReducers 메서드를 사용해서 하나의 Reducer로 합쳐줄 수 있음
action
어떤 액션을 취할 것인지 정의해 놓은 객체
→ type은 필수로 지정
→ 필요에 따라 payload를 작성해 구체적인 값을 전달
dispatch
reducer로 action을 전달해주는 함수
// 아래는 외우는 영역이다...
import { Provider } from 'react-redux';
import { createStore } from 'redux';
const 체중 = 100; //state 맘대로 보관가능
function reducer(state = 체중, action){
return state
}
let store = createStore(reducer)
ReactDOM.render(
<React.StrictMode>
<Provider store={store}>
<App />
</Provider>
</React.StrictMode>,
document.getElementById('root')
);
// Component에서 store에 있던 state 쓰려면
import './App.css';
import { useSelector } from 'react-redux'
function App() {
const 꺼내온거 = useSeletor((state) => state);
return(
<div className="App">
<p>님의 처참한 몸무게 : {꺼내온거}</p>
</div>
)
}
export default App;
// 꺼내온 거 = 100
//활용
import { Provider } from 'react-redux';
import { createStore } from 'redux';
const 체중 = 100; //state 맘대로 보관가능
function reducer(state = 체중, action){
// state 수정방법 //Reducer라고 부름
if(action.type === '증가'){
state++;
return state
} else if(action.type === '감소'){
state--;
return state
} else {
return state
}
}
let store = createStore(reducer)
ReactDOM.render(
<React.StrictMode>
<Provider store={store}>
<App />
</Provider>
</React.StrictMode>,
document.getElementById('root')
);
import './App.css';
import { useDispatch, useSelector } from 'react-redux'
function App() {
const 꺼내온거 = useSeletor((state) => state);
const dispatch = useDispatch()
return(
<div className="App">
<p>님의 처참한 몸무게 : {꺼내온거}</p>
// 컴포넌트에서 state 수정요청하려면? -> dispatch
<button onClick={()=>{dispatch({type: '증가'})}}>더하기</button>
</div>
)
}
export default App;
Redux Hooks
React-Redux에서 Redux를 사용할 때 활용할 수 있는 Hooks 메서드
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에 접근할 수 있게 해주는 메서드
// Redux Hooks 메서드는 'redux'가 아니라 'react-redux'에서 불러옵니다.
import { useSelector } from 'react-redux'
const counter = useSelector(state => state)
console.log(counter) // 1
Redux의 세 가지 원칙
- Single source of truth
- 동일한 데이터는 항상 같은 곳에서 가지고 와야 한다
- Redux에는 데이터를 저장하는 Store라는 단 하나뿐인 공간이 있음
- State is read-only
- 상태는 읽기 전용
- React에서 상태갱신함수로만 상태를 변경할 수 있었던 것처럼
Redux의 상태도 직접 변경할 수 없음 - Action 객체가 있어야만 상태를 변경할 수 있음
- Changes are made with pure functions
- 변경은 순수함수로만 가능하다
→ 엉뚱한 값으로 변경되는 일이 없도록 순수함수로 작성되어야 함
- 변경은 순수함수로만 가능하다