반응형
250x250
Notice
Recent Posts
Recent Comments
Link
관리 메뉴

짧은코딩

combineReducers의 중요성, useAppDispatch 훅스 사용시 유의점 본문

인프런, 유데미/Redux

combineReducers의 중요성, useAppDispatch 훅스 사용시 유의점

5_hyun 2022. 12. 7. 01:30

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에 ()를 뺐는데 이러면 코드가 실행되지 않는다. 따라서 ()까지 해주는 것을 유의해야한다.

728x90
반응형
Comments