컴포넌트 간의 데이터를 주고 받을 때 우리는 props를 떠올린다.
props는 상위 컴포넌트에서 하위 컴포넌트 방향으로 흘러가게 되어있는데, 이런 성격을 가지고 있어서 props drilling이라는 문제를 겪을 수 있다.
이런 props drilling의 문제를 보고 react의 데이터의 흐름을 더욱 효과적으로 파악하기 쉽게 하기 위해 생긴 것이 redux이다.
Context API 또한 전역 state를 만들어서 data를 관리할 수 있는데 왜 redux가 필요한 것일까?
Local State
컴포넌트 안에서 useState로 생성한 state
Global State
중앙 state 관리소(redux에선 store)에서 생성한 state
중앙 state 관리소를 사용할 수 있게 도와주는 패키지(라이브러리)이다.
redux
├─ config
│ └─ store 이름.js
└─ modules
└─ module 이름.js
const rootReducer = combineReducers({
//여기에 생성한, 사용할 모듈을 넣음
});
const store = createStore(rootReducer);
export default store;
<Provider store={store}>
<App />
</Provider>
const initialState = {
number: 0, //예시
}
const counter = (state = initialState, action) => {
switch(action.type) {
case "PLUS_NUM":
return state + 1;
break;
default:
return state;
break;
}
}
const counterReducer = useSelector((state)=>{
return state;
});
useSelector를 이용해서 만든 모듈안의 state값을 가져온다.