// store.js
import { configureStore } from "@reduxjs/toolkit";
export const store = configureStore({
reducer: {},
});
// index.js
import { store } from "./store";
import { Provider } from "react-redux";
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
<Provider store={store}>
<App />
</Provider>
);
// counterSlice.js
import { createSlice } from "@reduxjs/toolkit";
const initialState = {
value: 0,
name: "서현",
};
export const counterSlice = createSlice({
name: "counter",
initialState,
reducers: {
increment: (state) => {
state.value += 1;
},
decrement: (state) => {
state.value -= 1;
},
incrementByAmount: (state, action) => {
// action.payload? dispatch할 때 보내준 데이터
state.value += action.payload;
},
},
});
export const { increment, decrement, incrementByAmount } = counterSlice.actions;
export default counterSlice.reducer;
export const getValue = (state) => state.counters.value;
// state.counters <--- counters는 내가 store.js에서 붙여준 이름
// reducer: { counters: counterSlice },
// store.js
import { configureStore } from "@reduxjs/toolkit";
import counterSlice from "./counterSlice";
export const store = configureStore({
reducer: { counters: counterSlice },
});
// App.js
import { useState } from "react";
import { useSelector, useDispatch } from "react-redux";
import {
decrement,
increment,
incrementByAmount,
getValue
} from "./counterSlice";
function App() {
const count = useSelector((state) => state.counters.value);
const count2 = useSelector(getValue);
//count와 count2의 값은 똑같다
// 선생님이 count2의 방법으로 불러와서 사용하라고 했는데 이유는 까먹었다...
const dispatch = useDispatch();
const [incrementAmount, setIncrementAmount] = useState("2");
return (
<div>
<div>
<button
aria-label="Increment value"
onClick={() => dispatch(increment())}
>
Increment
</button>
<span>
{count},{count2}
</span>
<button
aria-label="Decrement value"
onClick={() => dispatch(decrement())}
>
Decrement
</button>
<input
aria-label="Set increment amount"
value={incrementAmount}
onChange={(e) => setIncrementAmount(e.target.value)}
/>
<button
onClick={() => dispatch(incrementByAmount(Number(incrementAmount)))}
>
Add Amount
</button>
<h2>{incrementAmount}</h2>
</div>
</div>
);
}
export default App;
공식문서에 타입스크립트로 설정하는 방법도 자세히 나와있음
나는 이렇게 친철한 공식문서가 좋아❤️
출처 -리덕스툴킷 공식문서