Redux(리덕스)란 javascript 상태(컴포넌트 내부에서 사용하는 데이터)관리 라이브러리이다.
props 없이 state(상태)를 공유할 수 있게 도와주는 라이브러리이다.
//main.jsx
import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App.jsx";
import "./index.css";
import { store } from "./store.js";
import { Provider } from "react-redux";
ReactDOM.createRoot(document.getElementById("root")).render(
<React.StrictMode>
<Provider store={store}>
<App />
</Provider>
</React.StrictMode>,
);
// app.jsx
import { useSelector, useDispatch } from "react-redux";
import { increment, decrement, incrementByAmount } from "./store";
export default function App() {
const count = useSelector((state) => state.counter.value);
const dispatch = useDispatch();
return (
<main>
<h1>Redux Toolkit Counter</h1>
<div>
<button onClick={() => dispatch(decrement())}>-</button>
<span>{count}</span>
<button onClick={() => dispatch(increment())}>+</button>
</div>
<div>
<button onClick={() => dispatch(incrementByAmount(5))}>
Increment by 5
</button>
</div>
</main>
);
}
// store.js
import { configureStore, createSlice } from "@reduxjs/toolkit";
export const counterSlice = createSlice({
name: "counter",
initialState: {
value: 0,
},
reducers: {
increment: (state) => {
state.value += 1;
},
decrement: (state) => {
state.value -= 1;
},
incrementByAmount: (state, action) => {
state.value += action.payload;
},
},
});
export const { increment, decrement, incrementByAmount } = counterSlice.actions;
export const store = configureStore({
reducer: {
counter: counterSlice.reducer,
},
});