[React] React-Readux 사용법

1. Redux

React-Redux는 React 애플리케이션에서 상태를 관리하는 라이브러리로, 전역 상태를 관리하는 패턴을 제공해 복잡한 애플리케이션에서 상태를 쉽게 관리하도록 도와줍니다. Redux의 특징으로는 다음과 같습니다.

  • 단일 스토어: 애플리케이션의 모든 상태를 하나의 스토어에서 관리, 이를 통해 애플리케이션의 상태를 중앙 집중식으로 관리할 수 있음
  • 불변성: 상태를 직접 수정하는 것이 아닌, 새로운 상태 객체를 반환해 상태를 변경, 이를 통해서 이전 상태를 보존하고, 상태 변경을 쉽게 추적
  • 순수 함수: 상태 변화는 순수 함수인 리듀서를 통해 이루어짐, 리듀서는 현재 상태와 액션을 입력받아 새로운 상태를 반환함
  • 미들웨어: Redux는 미들웨어를 통해 비동기 작업이나 로깅과 같은 추가 기능을 쉽게 적용할 수 있음
  • 디버깅 도구: Redux DevTools를 사용해 상태 변화와 액션을 쉽게 추적하고 디버깅

2. Redux 사용법

먼저 Redux를 사용하기 위해서는 React 프로젝트를 생성해야합니다. 아래 명령어로 React 프로젝트를 생성하고 Redux라이브러리를 설치해줍니다.

npx create-react-app react-redux-app
cd react-redux-app 
code . # vscode 열기
  • Redux 및 React-Redux 설치

먼저 Redux와 React-Redux 라이브러리를 설치해줍니다.

npm install redux react-redux
  • 스토어 생성

src 폴더에 store.js를 생성하고 리듀서를 설정합니다.

// src/store.js
import { createStore } from "redux";

// 초기 상태
const initialState = {
  count: 0,
};

// 리듀서 정의
const counterReducer = (state = initialState, action) => {
  switch (action.type) {
    case "INCREMENT":
      return { ...state, count: state.count + 1 };
    case "DECREMENT":
      return { ...state, count: state.count - 1 };
    default:
      return state;
  }
};

// 스토어 생성
const store = createStore(counterReducer);

export default store;

3. Redux Provider 설정

애플리케이션의 최상위 컴포넌트에 Redux Provider를 설정해 스토어를 제공합니다.

// index.js
import React from "react";
import ReactDOM from "react-dom/client";
import "./index.css";
import App from "./App";
import { Provider } from "react-redux";
import store from "./store";

ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById("root")
);

4. 상태 및 액션 사용

React 컴포넌트에서 Redux 상태를 사용하고 액션을 디스패치합니다.

// Counter.js
import React from "react";
import { useSelector, useDispatch } from "react-redux";

const Counter = () => {
  const count = useSelector((state) => state.count); // 상태 가져오기
  const dispatch = useDispatch(); // 디스패치 ㅅ함수 가져오기

  return (
    <div>
      <h1>Count: {count}</h1>
      <button onClick={() => dispatch({ type: "INCREMENT" })}>INCREMENT</button>
      <button onClick={() => dispatch({ type: "DECREMENT" })}>DECREMENT</button>
    </div>
  );
};
export default Counter;

5. 컴포넌트 사용

Counter 컴포넌트를 애플리케이션에 추가하고 앱을 실행합니다.

import React from "react";
import ReactDOM from "react-dom/client";
import "./index.css";
import App from "./App";
import { Provider } from "react-redux";
import store from "./store";

const container = document.getElementById("root");
const root = ReactDOM.createRoot(container); // createRoot 사용

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

6. 스토어 수정

카운터를 0이하로 내려가지 않게 수정하도록 Math 함수를 사용할 수 있습니다.

// src/store.js
import { createStore } from "redux";

// 초기 상태
const initialState = {
  count: 0,
};

// 리듀서 정의
const counterReducer = (state = initialState, action) => {
  switch (action.type) {
    case "INCREMENT":
      return { ...state, count: state.count + 1 };
    case "DECREMENT":
      return { ...state, count: Math.max(state.count - 1) };
    default:
      return state;
  }
};

// 스토어 생성
const store = createStore(counterReducer);

export default store;

 

Counter.js 파일에서 카운터를 표시하고 버튼이 0일때 감소를 비활성화하는 코드를 구현합니다.

// Counter.js
import React from "react";
import { useSelector, useDispatch } from "react-redux";

const Counter = () => {
  const count = useSelector((state) => state.count); // 상태 가져오기
  const dispatch = useDispatch(); // 디스패치 함수 가져오기

  return (
    <div>
      <h1>Count: {count}</h1>
      <button onClick={() => dispatch({ type: "INCREMENT" })}>INCREMENT</button>
      <button
        onClick={() => dispatch({ type: "DECREMENT" })}
        disabled={count === 0}
      >
        DECREMENT
      </button>
    </div>
  );
};
export default Counter;

 

 

GitHub - Koras02/react-redux-example

Contribute to Koras02/react-redux-example development by creating an account on GitHub.

github.com

 

LIST

'Front-End > ReactJS' 카테고리의 다른 글

[ReactJS] React + MySQL 게시판 만들기  (0) 2025.03.12
[React] React TMDB API를 사용한 리듀서 규현하기  (0) 2025.03.03
[ReactJS] 8장 Typescript  (0) 2025.02.27
[ReactJS] 7장 상태관리  (0) 2025.02.26
[ReactJS] 6장 폼  (0) 2025.02.25