createStore를 사용하려고 하면 createStore에 중앙선이 그어져있고 redux/toolkit의 configureStore메서드를 사용할 것을 추천한다는 메세지를 받을 수 있다.
그러므로 createStore로 작성했던 코드를 redux/toolkit을 사용하여 다시 작성해보겠다.
redux-thunk
- redux를 사용하는 어플리케이션에서 비동기 작업을 처리 할 때 사용하는 미들웨어이다.
- thunk란, 특정 작업을 나중에 하도록 미루기 위해서 함수형태로 감싼것을 칭한다.
- 이 미들웨어는 객체 대신 함수를 생성하는 액션 생성함수를 작성 할 수 있게 해줍니다.
export const notify = (message, dismissTime = 5000) => dispatch => {
const uuid = Math.random()
dispatch(enqueueNotification(message, dismissTime, uuid))
setTimeout(() => {
dispatch(dequeueNotification())
}, dismissTime)
}
createStore를 사용했을 때
const handleClick = (item) => {
dispatch(addToCart(item.id))
}
createStore를 사용할 때는 quantity(수량)을 actions creator 함수에서 quantity: 1 라고 정해준다음 cartItems에 넣어줬지만 이제는 actions creator 함수를 사용하지 않으므로 quantity: 1 을 직접 넣어서 addToCart 함수에 보내준다.
createSlice()
reducer 함수의 객체, 슬라이스 이름, 초기 상태 값을 받아들여서 해당 액션생성자와 액션 유형으로 slice reducer를 자동으로 생성한다.
createSlice는 다음과 같은 파라미터로 구성되어 있다.
Redux Toolkit allows us to write "mutating" logic in reducers.
It doesn't actually mutate the state because it uses the Immer library, which detects changes to a "draft state" and produces a brand new immutable state based off those changes
Redux Toolkit을 사용하면 "mutating(변이)" 방식으로 리듀서를 작성할 수 있다.
그것(Redux Toolkit)은 Immer 라이브러리를 사용하기 때문에 실제로 상태를 변형하지 않습니다.
그 라이브러리(Immer 라이브러리)는 초안 상태의 state에서 변경 사항을 감지하고, 이러한 변경 사항을 기반으로 완전히 새로운 immutable state를 만든다.
코드를 보며 의역을 하자면 ReduxToolkit을 사용하면 변경하는 방식으로 리듀서를 작성할 수 있고 변경 사항을 감지하여 변경 사항을 적용시켜 완전히 새로운 변경 불가능한(불변) state를 만든다.
addToCart : (state, action) => {
state.cartItems.push(action.payload)
},
removeFromCart : (state, action) => {
state.cartItems = state.cartItems.filter(el=>el.itemId !== action.payload)
},
components/CartItem.js
<button
className="cart-item-delete"
onClick={() => { handleDelete(item.id) }}>
삭제
</button>
setQuantity : (state, action) => {
console.log(action)
let idx = state.cartItems.findIndex(el => el.itemId === action.payload.itemId)
state.cartItems = [...state.cartItems.slice(0,idx), action.payload, ...state.cartItems.slice(idx+1)]
},
import { removeFromCart, setQuantity } from '../actions';
기존의 코드(위의 코드)를 아래 코드처럼 변경해준다.
import { removeFromCart, setQuantity } from '../reducers/itemReducer'
createStore 대신 redux/toolkit을 사용했을 때의 장점
1. redux-toolkit을 사용하므로써 actions를 작성해주지 않아도 된다.
2. 데이터를 변경할 때도 Object.assign()을 통해 새로운 데이터를 담은 객체를 만드는 번거로운 과정을 거치지 않아도 된다.
(2)를 길게 풀어 말하자면
데이터를 변경할 때도 Object.assign()을 통해 빈 객체에 기존의 데이터를 담았다가 다시 덮어 씌우는 과정을 거쳐 새로운 객체를 만드는 방법이 아닌 배열에 직접 push 한다던지 변경이 필요한 부분만 프로퍼티 값을 변경해주는 직관적이고 편리한 방법으로 데이터를 관리 할 수 있다.