-
TIL-2024.07.16 - TIL - Redux - 001. Redux 101> Frontend/React 2024. 7. 17. 09:27
목표
- Redux 란 ?
- 다른 State Management 에 비교했을 때, 장점
- 사용 방법
Redux 란 ?
- JS Application 을 위한 상태 관리 (State Management) 라이브러리로, Application 의 상태를 예측 가능하고 일관되게 전역에서 관리하기 위해서 사용
사용 이유
- React 의 State Management 라이브러리는 Redux 말고도 다양한 라이브러리가 있음.
- 대표적인 예로 Zustand, Mobx, Recoil 이 있는데, 아래 블로그 글 참고
- State Management에 3가지 방법 (Flux, Proxy, Atomic)이 있는데, 아래의 이유로 저는 Flux 패턴을 가장 선호.
- 선호 이유 1. 중앙 집중식 상태관리
- 선호 이유 2. 예측 가능성과 일관성- 선호 이유 3. 가장 많은 npm 다운로드를 기반으로 하는 커뮤니티와 생태계
- 선호 이유 4. Typescript 호환성 및 Redux DevTools
사용 방법
- 최근 Redux 은 toolkit 과 같이 사용되기에, Redux- toolkit 으로 사용방법을 알아보자
1. 설치
- Redux Toolkit과 React-Redux를 설치
npm install @reduxjs/toolkit react-redux
2. Slice 생성
- Slice 생성을 통한 상태와 리듀서 정의
// features/counter/counterSlice.js import { createSlice } from '@reduxjs/toolkit'; // Redux Toolkit에서 createSlice를 가져옵니다. const initialState = { value: 0 } const counterSlice = createSlice({ name: 'counter', // Slice의 이름을 정의합니다. 액션 타입을 생성할 때 사용. initialState: initialState, // 상태의 초기값을 설정. reducers: { increment: (state) => { // 'increment' 액션을 처리하는 reducer. state.value += 1; // 현재 상태에서 value 값을 1 증가. }, decrement: (state) => { // 'decrement' 액션을 처리하는 reducer. state.value -= 1; // 현재 상태에서 value 값을 1 감소. }, incrementByAmount: (state, action) => { // 'incrementByAmount' 액션을 처리하는 reducer. state.value += action.payload; // 현재 상태에서 action.payload 만큼 value 값을 증가. }, }, }); export const { increment, decrement, incrementByAmount } = counterSlice.actions; // 액션 생성자를 익스포트. export default counterSlice.reducer; // 리듀서를 익스포트하여 스토어에 추가.
3. Store 설정
- configureStore를 사용하여 Redux 스토어를 설정
// app/store.js import { configureStore } from '@reduxjs/toolkit'; // Redux Toolkit에서 configureStore를 가져옵니다. import counterReducer from '../features/counter/counterSlice'; // counterSlice에서 생성된 reducer를 가져옴. const store = configureStore({ reducer: { counter: counterReducer, // 스토어에 리듀서를 추가합니다. 'counter' 상태는 counterReducer로 관리됩니다. }, }); export default store;
4. Provider 로 스토어 설정
- React 애플리케이션에 Redux 스토어를 연결
// index.js import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; // React-Redux에서 Provider 컴포넌트를 가져옴. import store from './app/store'; // 설정된 Redux 스토어를 가져옴. import App from './App'; ReactDOM.render( <Provider store={store}> // Provider 컴포넌트로 애플리케이션을 감싸고, 스토어를 전달. <App /> </Provider>, document.getElementById('root') );
5. State 와 Action 사용
- React 컴포넌트에서 Redux 상태를 읽고, 액션을 디스패치
// App.js import React from 'react'; import { useSelector, useDispatch } from 'react-redux'; // React-Redux에서 useSelector와 useDispatch 가져옴. import { increment, decrement, incrementByAmount } from './features/counter/counterSlice'; // counterSlice에서 액션 생성자를 가져옴. function App() { const count = useSelector((state) => state.counter.value); // Redux 스토어의 counter 상태에서 value 값을 선택. const dispatch = useDispatch(); // useDispatch 훅을 사용하여 디스패치 함수를 가져옴. return ( <div> <h1>{count}</h1> // 현재 카운터 값을 화면에 표시합니다. <button onClick={() => dispatch(increment())}>Increment</button> // increment 액션을 디스패치하여 카운터 값을 증가시킵니다. <button onClick={() => dispatch(decrement())}>Decrement</button> // decrement 액션을 디스패치하여 카운터 값을 감소시킵니다. <button onClick={() => dispatch(incrementByAmount(5))}>Increment by 5</button> // incrementByAmount 액션을 디스패치하여 카운터 값을 5만큼 증가시킵니다. </div> ); } export default App;
'> Frontend > React' 카테고리의 다른 글
TIL-2024.07.18 - TIL - Redux - 003. redux-saga + redux-saga/effects (0) 2024.07.18 TIL-2024.07.17 - TIL - Redux - 002. ReduxSaga 101 (0) 2024.07.17 TIL-2024.07.11 - React - redux 기초 (0) 2024.07.11 TIL-2024.05.11 - Alias 설정 (0) 2024.05.11 TIL-2024.05.08 - React - 014. Styled Component - advanced- 1 (0) 2024.05.09