이번에는 기존에 사용하던 Redux에서 좀 더 업그레이드된 Redux toolkit에 대해 공부해보았다.
Redux가 솔직히 처음에는 너무 복잡하였지만 이제 좀 적응하려는데 Redux toolkit을 써야만 할까?
하던 중 막상 사용해보니 코드는 더 간결해지고 더 편해졌다.
어떻게 사용하는지 알아보자~
// 기존 Redux 사용시 reducer 파일
let initialState = {
itemList: [],
item: null,
};
const itemReducer = (state = initialState, action) => {
switch(action.type){
case 'GET_ITEMLIST' :
return {...state, itemList: payload.data};
case 'GET_ITEM' :
return {...state, item: payload.data};
default :
return {...state};
}
}
export default itemReducer;
// redux toolkit 사용시
import {createSlice} from '@reduxjs/toolkit'; // 우선 createSlice를 import 해준다.
let initialState = {
itemList: [],
item: null,
};
const itemSlice = createSlice({
name: 'item', // slice에 대한 이름, slice가 알아서 유니크한 action name을 만들어줌, 즉 action name은 직접 만들 필요가 없음
initialState, // 초기값
reducers: {
getAllItem: (state, action) => {
state.itemList = action.payload.itemList;
},
getItem: (state, action) => {
state.item = action.payload.item;
}
}
})
export const itemActions = itemSlice.actions; // 얘를 이렇게 내보내줘야 나중에 dispatch를 사용할때 불러 쓸수 있다.
export default itemSlice.reducer; // 위의 itemSlice 내부에는reducers라 되어있지만 내보내줄때는 reducer!
createSlice는 객체를 매개변수로 받는데,
객체에는 반드시 name, initialState, reducers라는 값이 있어야한다.
// 기존 redux 사용시 store
import {createStore, combineReducers} from 'redux';
import {itemReducer, counterReducer, searchReducer} from '../reducers'
const combinedReducer = combineReducers({
itemReducer,
counterReducer,
searchReducer,
})
let store = createStore(combinedReducer);
export default store;
// redux toolkit 사용시 store
import {configureStore} from '@reduxjs/toolkit';
import {itemSlice, counterSlice, searchSlice} from '../slices'
let store = configureStore({
reducer: {
isItemActions: itemSlice,
counterActions: counterSlice,
}
});
export default store;
redux toolkit을 사용함으로써 type을 쓰질 않았는데,
그럼 action을 call할때 뭘 입력해야할까??
import {useDispatch} from 'react-redux';
import {increase} from '../reducers';
const A = () => {
const dispatch = useDispatch();
const up = () => {
dispatch(increase())
}
}
import {useDispatch} from 'react-redux';
import {counterActions} from '../slices';
const A = () => {
const dispatch = useDispatch();
const getNumber = () => {
dispatch(counterActions.getNumber(data)) // 매개변수를 넣어주면 그 매개변수는 무조건 payload밑으로 들어가게 된다.
}
}