반응형
1. 라이브러리 설치
yarn add redux react-redux @reduxjs/tookit
2. index.js
Reducer 연결 및 store 생성
import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import App from "./App";
import reportWebVitals from "./reportWebVitals";
import { configureStore } from "@reduxjs/toolkit";
import rootReducer from "./reducers";
import { Provider } from "react-redux";
const store = configureStore({
reducer: rootReducer,
devTools: process.env.NODE_ENV !== "production",
});
ReactDOM.render(
<React.StrictMode>
<Provider store={store}>
<App />
</Provider>
</React.StrictMode>,
document.getElementById("root")
);
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();
3. App.js
import React from "react";
import "./App.css";
import Counter from './components/Counter';
const App = () => {
return (
<div>
<Counter />
</div>
);
};
export default App;
4. reducers/counter.js
import { createAction, createReducer } from "@reduxjs/toolkit";
const INCREASE = "counter/INCREASE";
const DECREASE = "counter/DECREASE";
export const increase = createAction(INCREASE);
export const decrease = createAction(DECREASE);
const initialState = {
number: 0,
};
const counter = createReducer(initialState, {
[INCREASE]: (state, action) => ({ number: state.number + 1 }),
[DECREASE]: (state, action) => ({ number: state.number - 1 }),
});
export default counter;
5.reducers/index.js
import { combineReducers } from "redux";
import counter from './counter';
const rootReducer = combineReducers({
counter,
})
export default rootReducer;
6. components/Counter.jsx
import React from "react";
import { increase, decrease } from "../reducers/counter";
import { useSelector, useDispatch } from "react-redux";
const Counter = () => {
const number = useSelector((state) => state.counter.number);
const dispatch = useDispatch();
return (
<div>
<h1>{number}</h1>
<div>
<button onClick={() => dispatch(increase())}>+1</button>
<button onClick={() => dispatch(decrease())}>-1</button>
</div>
</div>
);
};
export default Counter;
반응형
'Programming > React' 카테고리의 다른 글
개츠비(Gatsby) 마크다운 파일과 이미지 처리하기 (0) | 2023.07.30 |
---|---|
개츠비(Gatsby) 마크다운 블로그 만들기 시작하기 (0) | 2023.07.26 |
React에서 Kakao 지도 api 사용하기 - 지도에 표시하기 (0) | 2021.08.11 |
React에서 Kakao 지도 api 사용하기 (0) | 2021.08.10 |
Gatsby 시작하기 (with Typescript) (0) | 2021.07.04 |