공식 Redux 는 Redux Tookit 사용을 권장하고 있다
기존 Redux와 비교한 장점
⇒ 내부에 이미 포함되어 있음
설치
$ npm i @reduxjs/toolkit redux react-redux
$ npm i redux-action
store 설정
{
reducer: rootReducer
middleware: () => [ ... ]
devTools: true | false
preloadedState: {}
enhancers: (defaultEnhancers) => [...defaultEnhancers]
}
const logger = createLogger();
const sagaMiddleware = createSagaMiddleware();
const store = configureStore({
reducer: rootReducer,
middleware: () => [sagaMiddleware, logger],
});
Slice 생성
{
name: string,
initialState: any,
reducers: callback,
extraReducers?
}
// src/redux/slice/productSlice.js
import { createSlice } from "@reduxjs/toolkit";
const initialState = {
data: [],
};
export const productSlice = createSlice({
name: "product",
initialState,
reducers: {
getProductList: (state, action) => {
},
searchProduct: (state, action) => {
},
setProductList: (state, action) => {
console.log("set productList");
const products = action.payload;
state.data = [...products];
},
setSearchResult: (state, action) => {
console.log("set search result");
state.data = [...action.payload];
},
},
});
import React, { useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import { addToCart, clearCart, removeFromCart } from "./../redux/action";
import { getProductList } from "../redux/slice/productSlice";
const App = () => {
const dispatch = useDispatch();
const data = useSelector((state) => state.product.data);
useEffect(() => {
console.log("product list API call..");
dispatch(getProductList());
}, []);
...
}
root reducer 생성
import { combineReducers } from "@reduxjs/toolkit";
const rootReducer = combineReducers({
product: productSlice.reducer,
auth: authSlice.reducer,
});