상태관리 라이브러리
Redux 설치하면 store.js 같은 파일을 하나 만들고 state를 보관
2개의 인자를 전달받는 JavaScript함수
첫번째 인자 : state
두번째 인자 : action action : Redux의 state가 어떻게 변할지를 알려주는 인자 즉 action은 store에 보내는 일종의 데이터
// index.js
import {Provider} from "react-redux";
import {createStore} from "redux";
const weight = 100;
function reducer(state = weight,action){
if(action.type === "increase"){
state++;
return state;
}
else if(action.type === "decrease"){
state--;
return state;
}
else {
return state;
}
}
let store = createStore(reducer);
ReactDom.render(
<React.StrictMode>
<Provider store={store}>
<App/>
</Provider>
</React.StrictMode>
document.getElementById("root")
)
useSelector : setState의 초기값과 같은 역할
useDispatch : setState의 변경함수와 같은 역할
// App.js
import "./App.css";
import {useDispatch,useSelector} from "react-redux";
function App(){
const VarFromRedux = useSelector((state) => state); // 상태
const dispatch = useDispatch(); // 상태변경(상태 관리)
return (
<div>
<p>님의 몸무게 : {VarFromRedux}kg</p>
<button onClick={() => {dispatch({type:"increase"})}}>더하기</button>
</div>
)
}