redux-toolkit

김태완·2022년 4월 29일
0
post-thumbnail

회사에서 redux-toolkit을 쓰길래 한동안 기존 코드를 따라 사용했는데 이제 조금 이해가 되어 패턴을 정리해보자

redux-toolkit (RTK)이란?

기존의 복잡한 리덕스를 좀 더 편리하게 사용하기위한 툴킷.
기존의 리덕스는 redux외에 여러가지 모듈들을 추가로 설치해줘야했는데, RTK는 필요한 모듈들을 모두(saga제외)두 포함하고있다.

  • immer
  • react-redux
  • redux-thunk

설치

npm install @reduxjs/toolkit react-redux
yarn add @reduxjs/toolkit react-redux

메서드

  • createSlice : name, initialstate, reducer, extraReducer를 지정
  • createSelector : 리듀서의 특정 state를 선택해서 상태값으로 내보냄
  • configureStore : store생성
  • combineReducers : reducer들 묶기

RTK 패턴

RTK로 만든 간단한 counter예제이다. 정말... 간단하다 신세계임
다만 redux-saga를 사용한다면 추가 설정이 필요하다.

store/index.ts

import { configureStore, combineReducers } from '@reduxjs/toolkit';
import { counterReducer, COUNTER } from './modules/counter';

const rootReducer = combineReducers({
    [COUNTER]: counterReducer,
});

export const store = configureStore({
    reducer: rootReducer,
});

export type RootState = ReturnType<typeof rootReducer>;

store/modules/counter

import { createSlice, createSelector, PayloadAction } from '@reduxjs/toolkit';
import { RootState } from '../../';

export const COUNTER = 'counter';
interface CounterState {
    count: number;
}
const initialState: CounterState = {
    count: 0,
};

const counterSlice = createSlice({
    name: COUNTER,
    initialState,
    reducers: {
        setCountUp(state, action: PayloadAction<number>) {
            state.count = state.count + action.payload;
        },
    },
});

const selfSelector = (state: RootState) => state[COUNTER];

export const counterSelector = createSelector(selfSelector, (state) => state.count);

export const counterAction = counterSlice.actions;
export const counterReducer = counterSlice.reducer;

index.js

import { Provider } from 'react-redux';
import { store } from './store';

const root = ReactDOM.createRoot(document.getElementById('root') as HTMLElement);
root.render(
    <React.StrictMode>
        <Provider store={store}>
            <App />
        </Provider>
    </React.StrictMode>
);

custom hook으로 관리

store/modules/counter에서 selector,reducers가 많아지면 이를 커스텀 hooks에 묶어서 관리해주면 편리하다.
selector는 useMemo로, reducers는 useCallback으로 감싸서 최적화까지 해주면 완벽!

import { useSelector, useDispatch } from 'react-redux';
import { counterSelector, counterAction } from '../store/modules/counter';

const useCounter = () => {
    const dispatch = useDispatch();
    const count = useSelector(counterSelector);

    const setCountUp = (num: number) => {
        dispatch(counterAction.setCountUp(num));
    };

    return { count, setCountUp };
};

export default useCounter;

*git project : https://github.com/aptakqmf12/reduxToolkit

profile
프론트엔드개발

0개의 댓글