Redux 사용하기 - 계산기 만들기

목차

라이브러리 설치

Action 정의하기

export const INCREASE = "counter/INCREASE" as const;
export const DECREASE = "counter/DECREASE" as const;

interface increaseAction {
type: typeof INCREASE;
}

interface decreaseAction {
type: typeof DECREASE;
}

export type CounterType = increaseAction | decreaseAction;

Action 생성 함수

export const increase = (): increaseAction => ({
type: INCREASE,
});

export const decrease = (): decreaseAction => ({
type: DECREASE,
});

State

interface CounterState {
value: number;
}

const initialState: CounterState = {
value: 0,
};

Reducer

const CounterReducer = (
state = initialState,
action: CounterType
): CounterState => {
switch (action.type) {
case INCREASE:
return {
...state,
value: state.value + 1,
};
case DECREASE:
return {
...state,
value: state.value - 1,
};
default:
return state;
}
};

export default CounterReducer;
export type CounterReturnType = ReturnType<typeof CounterReducer>;

Store

import React from "react";
import ReactDOM from "react-dom/client";
import "./index.css";
import App from "./App";
import reportWebVitals from "./reportWebVitals";
import { applyMiddleware, createStore } from "redux";
import CounterReducer from "./redux/CounterReducer";
import { Provider } from "react-redux";
import { logger } from "redux-logger";

const store = createStore(CounterReducer, applyMiddleware(logger));

const root = ReactDOM.createRoot(
document.getElementById("root") as HTMLElement
);

root.render(
<React.StrictMode>
<Provider store={store}>
<App />
</Provider>
</React.StrictMode>
);

reportWebVitals();

App

import React, { useCallback, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { CounterReturnType, decrease, increase } from "./redux/CounterReducer";

function App() {
const { value } = useSelector((state: CounterReturnType) => ({
value: state.value,
}));

const dispatch = useDispatch();
const onClickIncrease = useCallback(() => {
dispatch(increase());
}, []);

const onClickDecrease = useCallback(() => {
dispatch(decrease());
}, []);

return (
<div className="App">
<div>{value}</div>
<button onClick={onClickIncrease}>+1</button>
<button onClick={onClickDecrease}>-1</button>
</div>
);
}

export default App;
Share