본문 바로가기
Programming/Javascript

React toolkit을 이용한 React counter

by Wilkyway 2021. 8. 23.
반응형

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;
반응형

댓글