일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
Tags
- async/await
- SSR
- dfs
- ESlint
- TS
- Jest
- 리터럴 타입
- 무한 스크롤
- map
- CORS
- Promise
- 이분 검색
- 결정 알고리즘
- useAppDispatch
- 공변성
- 타입 좁히기
- RTK Query
- 호이스팅
- 태그된 유니온
- recoil
- 투포인터
- app router
- CI/CD
- React
- tailwind
- 인터섹션
- 반공변성
- autosize
- Cypress
- webpack
Archives
- Today
- Total
짧은코딩
combineReducers의 중요성, useAppDispatch 훅스 사용시 유의점 본문
반응형
combineReducers
combineReducers는 Reducer들을 모두 합쳐주는 것이다. 이것이 중요한 이유는 store에서 reducer를 단 1개만 받을 수 있기 때문이다. 따라서 combineReducers에서 Reducer들을 모두 합쳐주고 store에서 모두 합쳐진 reducer를 사용하면 된다.
사용 방법
reducers/index.ts
import { combineReducers } from '@reduxjs/toolkit';
import { testSlice } from './TestSlice';
import { roadMapSlice } from './RoadMapSlice';
const reducer = combineReducers({
test: testSlice.reducer,
roadMap: roadMapSlice.reducer,
});
export default reducer;
reducers 폴더에서 index.ts 파일을 만들고 reducer에 combineReducers를 통해서 reducer들을 다 합쳐준다.
store.ts
import { configureStore, ThunkAction, Action } from '@reduxjs/toolkit';
import reducer from '../reducers';
export const store = configureStore({
reducer,
});
export type AppDispatch = typeof store.dispatch;
export type RootState = ReturnType<typeof store.getState>;
export type AppThunk<ReturnType = void> = ThunkAction<ReturnType, RootState, unknown, Action<string>>;
store.ts에 reducers/index.ts에서 만든 reducer를 불러와서 사용해주면 모든 reducer들을 사용할 수 있다.
useAppDispatch 훅스 사용시 주의점
const dispatch = useAppDispatch();
보통 이렇게 dispatch로 하여 사용을 한다.
-옳바른 예시
const onClickOrderEdit = useCallback(() => {
dispatch(toggleOrderEdit());
}, []);
dispatch에서 action을 사용한다.
-틀린 예시
const onClickOrderEdit = useCallback(() => {
dispatch(toggleOrderEdit);
}, []);
여기에선 action에 ()를 뺐는데 이러면 코드가 실행되지 않는다. 따라서 ()까지 해주는 것을 유의해야한다.
반응형
'인프런, 유데미 > Redux' 카테고리의 다른 글
redux-saga (0) | 2022.12.27 |
---|---|
리덕스 툴킷 TS로 리액트와 연동하기(기본 폴더 구조) (1) | 2022.11.28 |
redux-toolkit (0) | 2022.11.19 |
immer(코드를 줄일 수 있음) (0) | 2022.11.18 |
리액트와 리덕스 연결하기, redux devtools (0) | 2022.11.18 |
Comments