📁 index.js
import React from "react";
import ReactDOM from "react-dom/client";
import "./index.css";
import App from "./App";
import reportWebVitals from "./reportWebVitals";
import { Provider } from "react-redux";
import store from "./redux/config/configStore";
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
<Provider store={store}>
<App />
</Provider>
);
reportWebVitals();
📁 App.jsx
import logo from './logo.svg';
import './App.css';
import { useDispatch, useSelector } from 'react-redux';
import { addNumber, minusNumber } from './redux/modules/counter'
function App() {
const number = useSelector((state) => state.counter.number);
const dispatch = useDispatch();
const onPlusButtonclickHandler = () => {
dispatch(addNumber(1));
};
const onMinusButtonClickHandler = () => {
dispatch(minusNumber(1))
}
return (
<div>
{number}
<br />
<button onClick={onPlusButtonclickHandler}>+</button>
<button onClick={onMinusButtonClickHandler}>-</button>
</div>
);
}
export default App;
📁 redux / config / configStore.js
import counter from "../modules/counter";
const { combineReducers, createStore } = require("@reduxjs/toolkit");
const rootReducer = combineReducers({
counter: counter,
});
const store = createStore(rootReducer);
export default store;
📁 redux / modules / counter.js
// action value
const Add_NUMBER = "ADD_NUMBER"
const MINUS_Add_NUMBER = "MINUS_NUMBER"
// Action Creator
export const addNumber = (payload) => {
return {
type: ADD_NUMBER,
payload,
};
};
export const minusNumber = (payload) => {
return {
type: MINUS_NUMBER,
payload,
};
};
// 초기 상태(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 counter
yarn add @reduxjs/toolkit react-redux
📁 redux / config / configStore.js
import counter from "../modules/counter";
const { configureStore } = require("@reduxjs/toolkit");
const store = configureStore({
reducer: {
counter: counter,
}
})
export default store;
createStore
-> configureStore
📁 redux / modules / counter.js
createSlice
: acion creator
, reducer
를 한번에 생성할 수 있게 도와준다import { createSlice } from "@reduxjs/toolkit"
// 초기 상태(state)
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 default counterSlice.reducer
export const {addNumber, minusNumber} = counterSlice.actions
counterSlice
안에 creator
, reducer
담겨있다.reducers
안에 reducer
가 담겨있고, creator
가 자동 생성 된다.