죽이죽이
React : Redux 사용하기 본문
Redux 사용하기
※ 리덕스의 기본 원리
※ Redux 설치
- react-redux : react 환경에서 redux를 사용할 수 있게 해주는 라이브러리이다.
npm i redux react-redux
※ 기본 사용법
- App.jsimport Counter from './components/Counter'; function App() { return ( <Counter /> ); } export default App;
- Counter.jsimport classes from './Counter.module.css'; const Counter = () => { const toggleCounterHandler = () => {}; return ( <main className={classes.counter}> <h1>Redux Counter</h1> <div className={classes.value}>-- 카운터 값 --</div> <button onClick={toggleCounterHandler}>토글 카운터</button> </main> ); }; export default Counter;
- 실행 화면
- 기본 폴더 구조
- Reducer, Store 생성import { createStore } from "redux"; const counterReducer = (state = { counter: 0 }, action) => { // action의 타입이 increment일 경우 이전 상태의 값 1 증가 if (action.type === "increment") { return { counter: state.counter + 1, }; } // action의 타입이 decrement일 경우 이전 상태의 값 1 감소 if (action.type === "decrement") { return { counter: state.counter - 1, }; } return state; }; const store = createStore(counterReducer); export default store;
- Provider로 앱의 최상단 감싸주기const root = ReactDOM.createRoot(document.getElementById("root")); root.render( <Provider store={store}> <App /> </Provider> );
- useSelector : Store에서 상태값을 읽어오는데 사용한다.const counter = useSelector((state) => state.counter); return ( <main className={classes.counter}> <h1>Redux Counter</h1> <div className={classes.value}>{counter}</div> <button onClick={toggleCounterHandler}>토글 카운터</button> </main> );
- useDispatch : 액션을 reducer에 전달해서 상태값에 대한 특정 작업을 하는데 사용한다.const dispatch = useDispatch(); const handleIncrement = () => { dispatch({ type: "increment" }); }; const handleDecrement = () => { dispatch({ type: "decrement" }); }; return ( <main className={classes.counter}> <h1>Redux Counter</h1> <div className={classes.value}>{counter}</div> <button onClick={toggleCounterHandler}>토글 카운터</button> <button onClick={handleIncrement}>숫자 증가</button> <button onClick={handleDecrement}>숫자 감소</button> </main> );
- 주의할 점// Reducer에서 관리하는 상태값이 여러개일 경우 const counterReducer = (state = { counter: 0, showCounter: true }, action) => { if (action.type === "toggle") { return { ...state, // 이전 값들을 지정해주지 않을 경우 state가 덮어씌워진다. showCounter: !state.showCounter, }; }
'React' 카테고리의 다른 글
React : Redux 비동기 처리 (0) | 2024.02.27 |
---|---|
React : Redux ToolKit (RTK) (0) | 2024.02.27 |
React : Redux란? (0) | 2024.02.26 |
React : Form 유효성 검사 3가지 방식 (1) | 2024.02.26 |
React : Custom Hook (0) | 2024.02.23 |