Redux ์ค์น ์ํ๋ ๋ฒ์ ์ด ์๋ค๋ฉด @๋ฒ์ ๋ฒํธ ์ถ๊ฐ

Redux Store(์ด๊ด์ฑ ์์) ์์ฑ (.js ํ์ผ๋ก ์์ฑ) ๊ฒฝ๋ก ์์) src/store/store.js
Slices(์ต์๋จ์ ํ์ผ) ์์ฑ((.js ํ์ผ๋ก ์์ฑ) ๊ฒฝ๋ก ์์) src/store/slices/.js ํน์ src/store/modules/.js
// src/store/slices/list.js
import { createSlice } from "@reduxjs/toolkit";
// 'list' ์ํ๊ด๋ฆฌ slice ์์ฑ ๋ฐ ์ค์
const list = createSlice({
name: 'list', // silce ๋ช
initialState: { // ์ํ ๊ด๋ฆฌํ state๋ฅผ ์ ์ํ๋ ์ญ์ญ
cnt: 0,
},
reducers: { // state์ ์ํ๋ฅผ ๋ณํ์ํค๋ actions๋ฅผ ์ ์ํ๋ ์ญ์ญ
addCnt(state) { // state: initialState์์ญ
state.cnt += 1;
},
minusCnt(state) {
state.cnt -= 1;
},
changeCnt(state, action) {
// state: 'initialState'์ ์ ๋ณด๋ฅผ ๋ด๊ณ ์๋ ํ๋ผ๋ฏธํฐ
// action: ์ธ๋ถ์์ ์ ๋ฌ ๋ ๊ฐ์ ๋ด๋ ํ๋ผ๋ฏธํฐ
// >action.payload: ์ ๋ฌ๋ ๊ฐ์ ์ ๊ทผํ ์ ์๋ ํ๋กํผํฐ
state.cnt = action.payload;
},
}
});
// ์ ์ํ Actions ๋ด๋ณด๋ด๊ธฐ
// ์ปดํฌ๋ํธ์์ ํธ์ถ
export const {addCnt, minusCnt, changeCnt} = list.actions;
// Reducer ๋ด๋ณด๋ด๊ธฐ
// Store์์ ํธ์ถ
export default list.reducer;
์์ฑํ Slices๋ฅผ Store์ ์ถ๊ฐ
// src/store/store.js
import { configureStore } from "@reduxjs/toolkit";
import listReducer from "./slices/list.js";
// Redux Store ์์ฑ ๋ฐ ์ค์
export default configureStore({
reducer: {
list: listReducer,
}
});
main.jsx์ React Redux <Provider> ์ถ๊ฐ (StrctMode๋ฅผ ์ ์ธํ ์น์์ ์ปดํฌ๋ํธ์ผ ๊ฒ)
// main.jsx
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import App from './App.jsx';
import { Provider } from 'react-redux';
import store from './store/store.js';
createRoot(document.getElementById('root')).render(
<StrictMode>
<Provider store={store}>
<App />
</Provider>
</StrictMode>
);
๋ฑ๋กํ Redux ์ฌ์ฉ
useSelector ํ
์ ์ํฌํธconst ๋ณ์๋ช
= useSelector(state => state.๊ฐ์ ธ์ฌ slices.๊ฐ์ ธ์ฌ state์ ์์ฑ); ์ ํตํด State ํ๋const dispatch = useDispatch(); ์ ์ก์
์ ๋์คํจ์นํ ์ ์๋ ํจ์ ํ๋dispatch(์ก์
๋ช
()) ์ ์ด์ฉํด Action ํธ์ถ// List.jsx
import { useDispatch, useSelector } from 'react-redux';
import './List.css';
import { addCnt, minusCnt } from '../store/slices/list';
function List() {
// State์ ์ ๊ทผํ๋ ๋ฐฉ๋ฒ
// state๋ store์ด๊ธฐ ๋๋ฌธ์ slice ๋ช
๋ ํจ๊ป ์ ์ด ์ ๊ทผํจ
const cnt = useSelector(state => state.list.cnt);
// action ํธ์ถ ๋ฐฉ๋ฒ
const dispatch = useDispatch();
return (
<>
<h1>๋ฆฌ์คํธ ํ์ด์ง</h1>
<p>{cnt}</p>
<button type="button" onClick={() => { dispatch(minusCnt()) }}>-</button>
<button type="button" onClick={() => { dispatch(addCnt()) }}>+</button>
</>
);
}
export default List;
// App.jsx
import './App.css';
import List from './components/List.jsx';
function App() {
return (
<>
<List></List>
</>
)
}
export default App;