전역에서 상태 관리함으로써 애플리케이션 상태 변화와 로직의 동작을 더 이해하기 쉽고, 예측이 가능해진다.
1. CRA를 사용하는 경우
# redux + plain js template
npx create-react-app my-app --template redux
# redux + typescript template
npx create-react-app my-app --template redux-typescript
2. 기존 앱에서 라이브러리 추가하는 경우
# NPM
npm install @reduxjs/toolkit
# Yarn
yarn add @reduxjs/toolkit
src/index.js
import { Provider } from 'react-redux';
import { createStore } from 'redux';
const defaultWeight = 100; // 전역에 다룰수 있는 상태를 선언 및 초기 값 할당
function reducer(state = defaultWeight, action) { // state 수정하는 방법은 reducer 안에서 명시한다.
if(action.type === 'increase') {
state++;
return state;
} else if(action.type === 'decrease') {
state--;
return state;
} else {
return state;
}
}
let store = createStore(reducer); // createStore에 정의한 reducer를 인자로 넣어준다.
ReactDOM.render(
<React.StrictMode>
<Provider store={store}> {/* Provider에 store 속성을 준다. */}
<App />
</Provider>
</React.StrictMode>,
document.getElementById('root');
);
src/app.js
import './App.css';
import { useSelector, useDispatch } from 'react-redux';
function App() {
const yourWeight = useSelector((state) => state); // 전역에 다룬 상태를 꺼냄, 100
const dispatch = useDispatch();
return (
<div className="App">
<p>당신의 몸무게 : {yourWeight}</p> {/* 당신의 몸무게 : 100 */}
<button onClick={() => { dispatch({type : 'increase'}) }} >더하기</button>
</div>
);
}
export deafult App;