- Redux Toolkit: Redux를 사용하는데 있어서 Boiler-plate, 긴 상용구 코드 등을 매번 코딩해야 했던 불편한 점들을 최소한의 코드로 사용할 수 있게 만들어줌.
- 설치:
npm install @reduxjs/toolkit
- createAction: Redux action type 및 creator를 정의하기 위한 helper 함수.
- createReducer: Switch, Case문 대신에 새로운 형태를 사용하며 기존의 Redux에서는 불가했던 State의 Mutate(변형)를 가능하게 해 줌. 즉, State를 Mutate하거나 새로운 State를 Return해야 함(뭔가를 return하려면 새로운 state여야 함).
- 예시로 아래 코드를 보면 .push는 array 즉 State를 mutate하는 함수이고, .filter함수는 새로운 State를 return하는 것이다.
const reducer = createReducer([], {
[addToDo]: (state, action) => {
state.push({ text: action.payload, id: Date.now() });
},
[deleteToDo]: (state, action) =>
state.filter((toDo) => toDo.id !== action.payload),
});
- configureStore: Google Chrome의 확장 프로그램인 Redux DevTools라는 Middle-ware와 함께 Store를 생성하는 함수.
- createSlice: Reducer와 Action을 제공하는 함수
const toDos = createSlice({
name: "toDosReducer",
initialState: [],
reducers: {
add: (state, action) => {
state.push({ text: action.payload, id: Date.now() });
},
remove: (state, action) =>
state.filter((toDo) => toDo.id !== action.payload),
},
});
const store = configureStore({ reducer: toDos.reducer });
export const { add, remove } = toDos.actions;
- combineReducers: 2개 이상의 Reducer를 사용해야하는 경우 사용하는 함수
import { legacy_createStore } from "redux";
const ADD = "ADD";
const DELETE = "DELETE";
export const addToDo = (text) => {
return {
type: ADD,
text,
};
};
export const deleteToDo = (id) => {
return {
type: DELETE,
id,
};
};
const reducer = (state = [], action) => {
switch (action.type) {
case ADD:
return [{ text: action.text, id: Date.now() }, ...state];
case DELETE:
return state.filter((toDo) => toDo.id !== action.id);
default:
return state;
}
};
const store = legacy_createStore(reducer);
export default store;
import { legacy_createStore } from "redux";
import { configureStore, createAction, createReducer } from "@reduxjs/toolkit";
const addToDo = createAction("ADD");
const deleteToDo = createAction("DELETE");
const reducer = createReducer([], {
[addToDo]: (state, action) => {
state.push({ text: action.payload, id: Date.now() });
},
[deleteToDo]: (state, action) =>
state.filter((toDo) => toDo.id !== action.payload),
});
const store = configureStore({ reducer });
export default store;
import { configureStore, createSlice } from "@reduxjs/toolkit";
const toDos = createSlice({
name: "toDosReducer",
initialState: [],
reducers: {
add: (state, action) => {
state.push({ text: action.payload, id: Date.now() });
},
remove: (state, action) =>
state.filter((toDo) => toDo.id !== action.payload),
},
});
const store = configureStore({ reducer: toDos.reducer });
export const { add, remove } = toDos.actions;
export default store;