React Redux 사용 예

React Redux 사용 예

소개

React는 현재 가장 인기 있는 프론트엔드 프레임워크 중 하나입니다.

React를 조금 더 쉽게 다룰 수 있게 해주는 Redux를 살펴보겠습니다.

이 글에서는 예제를 통해 React와 Redux를 함께 사용하는 방법을 살펴보겠습니다.

리덕스란?

Redux는 JavaScript 애플리케이션에서 상태 관리에 사용되는 도구입니다.

React에서 상태를 관리하기 위해서는 props를 사용하여 상태를 전달해야 했습니다.

그러나 Redux는 전역적으로 상태를 관리하므로 여러 구성 요소에서 동시에 참조하고 사용할 수 있습니다.

React와 Redux 연결하기

React와 함께 Redux를 사용하려면 react-redux 라이브러리를 사용할 수 있습니다.

이 라이브러리를 사용하면 Redux 스토어를 React 구성 요소에 연결할 수 있습니다.

import React from 'react';
import { Provider } from 'react-redux';
import { createStore } from 'redux';
import rootReducer from './reducers';
import App from './App';

const store = createStore(rootReducer);

const ReduxApp = () => (
  <Provider store={store}>
    <App />
  </Provider>
);

export default ReduxApp;

Redux 사용 예

Redux를 사용하여 간단한 카운터 애플리케이션을 만들어 봅시다.

먼저 액션 유형과 액션 생성자를 정의합니다.

export const INCREMENT = 'INCREMENT';
export const DECREMENT = 'DECREMENT';

export const increment = () => ({
  type: INCREMENT,
});

export const decrement = () => ({
  type: DECREMENT,
});

그리고 감속기를 정의하십시오.

import { INCREMENT, DECREMENT } from '../actions';

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;
  }
};

export default counterReducer;

마지막으로 컴포넌트를 정의하고 Redux 스토어에 연결합니다.

import React from 'react';
import { connect } from 'react-redux';
import { increment, decrement } from './actions';

const Counter = ({ count, increment, decrement }) => (
  <div>
    <h1>{count}</h1>
    <button onClick={decrement}>-</button>
    <button onClick={increment}>+</button>
  </div>
);

const mapStateToProps = state => ({
  count: state.count,
});

const mapDispatchToProps = {
  increment,
  decrement,
};

export default connect(mapStateToProps, mapDispatchToProps)(Counter);

이렇게 작성된 코드가 실행되면 카운터 어플리케이션이 화면에 나타납니다.

결론

Redux는 상태 관리를 보다 효율적으로 만들기 위해 React에서 사용되는 라이브러리입니다.

이번 글에서는 Redux 사용법과 예제에 대해 알아보았습니다.

Redux는 React의 복잡한 상태 관리를 보다 효율적으로 만듭니다.