모듈 파일에서 리덕스를 더 편하게 쓰기 위함 !
redux toolkit 구글링하면 공식사이트 나옴
설치
yarn add @reduxjs/toolkit
or 리덕스 설치할때 툴킷 같이 설치해버리기 yarn add react-redux @reduxjs/toolkit
사용법
createSlice() 슬라이스로 리듀서를 한번에 만든다.
이제 Action Value와 Action Creator를 직접 생성해주지 않고,
Action Value, Action Creator, Reducer가 하나로 합쳐짐
(src/redux/modules/counterSlice.js)
import { createSlice } from '@reduxjs/toolkit';
// 초기 상태값(state)
const initialState = {
number: 0,
};
// ⭐슬라이스로 한번에 리듀서 만듦. 액션 크리에이터와 리듀서를 한번에 생성할 수 있게끔
// counterSlise로 저장해두면 안에 액션크리에이터와 리듀서 둘다 들어가있음
// 안에 키 벨류 객체가 들어감
// 인자{} : name, initialState, reducers(리듀서가 자동으로 만들어지는 것과 동시에
// 저 이름으로 action creator가 만들어져서 내보낼 수 있게 됨)
const counterSlice = createSlice({
name: 'counter', // 이 모듈의 이름
initialState, // 이 모듈의 초기상태 값
reducers: { // 이 모듈의 Reducer 로직
addNumber: (state, action) => {
// 리듀서를 의미하는 동시에 이름이 액션 크리에이터로 쓰임
// 기존엔 불변성을 유지시키기 위해 새로운 배열을 return하는 방식을 사용해왔음
// 근데 리덕스 툴킷에선 push같은걸 써도 잘됨
// redux toolkit안에 immer(불변성을 유지시켜줌)라는 기능이 내장되어 있기 때문!
state.number += action.payload;
},
minusNumber: (state, action) => {
state.number -= action.payload;
},
},
});
// 내보내기
// 리덕스 툴킷에서는 [slice]
// 기존방법 1. export. 내보낸거 -> 액션 크리에이터 3개를 내보내서 dispatch할때 사용
// 기존방법 2. export. 리듀서를 직접 만들었다
// 기존방법 3. action value도 정의했었음
// 액션크리에이터는 컴포넌트에서 사용하기 위해 export 하고
export const { addNumber, minusNumber } = counterSlice.actions;
// reducer 는 configStore에 등록하기 위해 export default 합니다.
export default counterSlice.reducer;
(src/redux/config/configStore.js)
import { configureStore } from '@reduxjs/toolkit';
// import { createStore } from 'redux';
// import { combineReducers } from 'redux';
// import todos from '../modules/todos';
// slice.reducer를 import해오기
import counter from '../modules/couterSlice'; // counter라는 리듀서를 임포트
import todos from '../modules/todosSlice';
// ASIS: 일반 리듀서. 이제 리덕스 툴킷에선 안씀
// // 1. create rootReducer with reducers
// const rootReducer = combineReducers({
// todos,
// });
// // 2. create store
// const store = createStore(rootReducer);
// TODO: Redux Toolkit
// 이젠 하나의 api만 쓸거. configureStore
// 안에는 객체가 들어가는데 리듀서가 들어감. counter.js에서 가져올거. key-value pair로 들어감
const store = configureStore({
reducer: {
counter,
todos,
},
});
// 3. export
// store를 사용해서 application에 주입하는 단계가 필요
export default store;
(src/index.js)
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import { Provider } from 'react-redux';
import store from './redux/config/configStore.js';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
// <React.StrictMode>
// 하부에서 store 쓸 수 있음. import필요
<Provider store={store}>
<App />
</Provider>
// </React.StrictMode>
);
조회/수정은 일반 redux와 같음
// 조회
const {number} = useSelector((state) => state.counter);
// 수정
const dispatch = useDispatch();
dispatch(addNumber(number));
플럭스 패턴
읽어보기!
https://bestalign.github.io/translation/cartoon-guide-to-flux/
Flux로의 카툰 안내서
원문: https://medium.com/code-cartoons/a-cartoon-guide-to-flux-6157355ab207 Flux…
bestalign.github.io
https://taegon.kim/archives/5288
Flux와 Redux
이 글에서는 Facebook에서 React와 함께 소개한 Flux 아키텍처에 대해 알아보고 Flux를 구현한 Redux 라이브러리를 살펴본 후 이를 적용한 간단한 React 애플리케이션을 작성해보겠다. 본문에 사용된 코
taegon.kim
'React' 카테고리의 다른 글
| json-server (0) | 2023.07.06 |
|---|---|
| Redux Devtools (0) | 2023.07.06 |
| JSON 기초 (0) | 2023.06.21 |
| 비동기 프로그래밍 (0) | 2023.06.21 |
| React Router Dom (0) | 2023.06.21 |