"전역" 상태를 관리하는 데 도움을 주는 Redux
Redux의 고충
을 해결하기 위해 만들어진 Redux toolkitnpm install @reduxjs/toolkit
#React bindings
npm install @reduxjs/toolkit react-redux
#or
yarn add @reduxjs/toolkit
#React bindings
yarn add @reduxjs/toolkit react-redux
configureStore()
import { createStore } from "redux";
import { combineReducers } from "redux";
import counter from "src/redux/modules/counter";
const rootReducer = combineReducers({
counter,
});
const store = createStore(rootReducer);
export default store;
import { configureStore } from "@reduxjs/toolkit";
import counter from "src/redux/modules/counterSlice";
import todos from "src/redux/modules/todosSlice";
const store = configureStore({
reducer: { counter: counter, todos: todos },
});
export default store;
createSlice()
// Action Value
const ADD_NUMBER = "ADD_NUMBER";
const MINUS_NUMBER = "MINUS_NUMBER";
// Action Creator
export const addNumber = (payload) => {
return {
type: ADD_NUMBER,
payload,
};
};
export const minusNumber = (payload) => {
return {
type: MINUS_NUMBER,
payload,
};
};
// Initial State
const initialState = {
number: 0,
};
// Reducer
const counter = (state = initialState, action) => {
switch (action.type) {
case ADD_NUMBER:
return {
number: state.number + action.payload,
};
// [퀴즈 답]
case MINUS_NUMBER:
return {
number: state.number - action.payload,
};
default:
return state;
}
};
// export default reducer
export default counter;
import { createSlice } from "@reduxjs/toolkit";
const initialState = {
number: 0,
};
const counterSlice = createSlice({
name: "counter",
initialState,
reducers: {
addNumber: (state, action) => {
state.number = state.number + action.payload;
},
minusNumber: (state, action) => {
state.number = state.number - action.payload;
},
},
});
export const { addNumber, minusNumber } = counterSlice.actions;
export default counterSlice.reducer;