티스토리 뷰

React

[React] Redux 사용 방법

ljy98 2022. 5. 10. 14:40

1. Redux 개념

2. Redux에서 사용되는 키워드

3. Redux의 3가지 원칙

4. Redux 사용 방법

5. Redux 보완점


1. Redux 개념

[그림 1] Redux 로고

Redux는 JavaScript app을 위한 state container이다. React 뿐만 아니라 Angular, jQuery, vanilla JavaScript 등 다양한 framework와 작동되도록 설계되었다. 즉, React만을 위한 Library는 아니다.

 

[그림 2] Redux의 호환성

Redux는 React의 좋은 보완재라고 할 수 있다. 그 이유는 action에 반응하여 상태를 변경하므로 React와 같이 UI를 상태에 대한 함수로 기술하는 framework와 특히 잘 어울리기 때문이다.

 

Q. React에 Redux가 필요한 이유는 무엇일까?

React로 프로젝트를 진행하게 되면 각각의 Component는 local state를 갖게 되고, 애플리케이션은 global state를 갖게 된다. 이 때 애플리케이션에서 global state와 local state를 관리하기가 어렵다.

특히 프로젝트의 규모가 클 경우 state를 props를 통해 계속 전달해 나가야 하기 때문에 불필요한 data의 흐름이 발생하게 되고, 제대로 props가 전달되지 않은 경우에는 중간에 끼인 모든 Component에서 일일이 문제점을 찾아보아야 하는 번거로움이 있다.

하지만, Redux를 사용하게 되면 하나의 store를 통해 global state를 포함한 모든 state를 저장하고 유지할 수 있게 되며, 원하는 Component로만 data를 전달할 수 있다.

 

 

2. Redux에서 사용되는 키워드

[그림 3] Redux 구성 요소

  • Action : state에 변화가 필요할 때 발생시킴 (하나의 객체로 표현) type을 필수로 그 외의 값들은 개발자 마음대로 생성
  • Action Creator : Component에서 더욱 쉽게 Action을 발생시키기 위함
  • Reducer : 변화를 일으키는 함수. 현재의 state와 action을 참조하여 새로운 상태를 반환
  • Store : 한 애플리케이션 당 하나의 Store가 있음. 현재의 앱 상태와 Reducer, 내장함수 포함
  • dispatch : Store의 내장함수. Action을 발생시키는 것
  • subscribe : Store의 내장함수. subscribe 함수에 특정 함수를 전달해주면, Action이 dispatch되었을 때 마다 전달해준 함수가 호출 (React에서는 connect 함수 또는 useSelector Hook을 사용)

 

 

3. Redux의 3가지 원칙

(1) Single source of truth

- 동일한 데이터는 항상 같은 곳에서 가지고 온다.

- 즉, Store라는 하나뿐인 데이터 공간이 있다는 의미이다.

 

(2) State is read-only

- React에서는 setState 메소드를 활용해야만 상태 변경이 가능하다.

- Redux에서는 action이라는 객체를 통해서만 상태를 변경할 수 있다.

 

(3) Changes are made with pure functions

- 변경은 순수 함수로만 가능하다.

- Reducer와 연관되는 개념이다.

- Store - Action - Reducer

 

 

4. Redux 사용 방법

React에서 Redux를 적용해 사용하려면, 먼저 아래 명령어로 필요한 패키지들을 설치해야 한다.

$ npm i redux react-redux redux-devtools-extension

redux-devtools-extension은 크롬 확장 프로그램에서 redux dev tools를 통해 설치할 수 있고, redux의 데이터 흐름을 알아보기 쉽게 하기 위해 사용한다.

 

4.1. rootReducer 정의

// reducers/index.js

import { combineReducers } from 'redux';
import counter from './counter';

const rootReducer = combineReducers({
	counter
});

export default rootReducer;

combineReducers는 여러 reducer를 사용하는 경우 reducer들을 하나로 묶어주는 메소드이다. store에 저장되는 reducer는 오직 1개이다.

 

4.2. 세부 reducer 정의

// reducers/counter.js

export const INCREASE = "COUNT/INCREASE";

export const increaseCount = count => ({ type: INCREASE, count });

const initialState = {
	count: 0
};

const counter = (state = initialState, action) => {
	switch (action.type) {
    	case INCREASE:
      		return {
        		...state,
        		count: action.count
      		};
    	default:
      		return state;
  	}
};

switch문에서 default를 쓰지 않으면 맨 처음 state에 count 값이 undefined가 나오므로, default case를 작성해 주어야 한다.

 

4.3. app에 store 추가, reducer 반영

// index.js
import React from "react";
import ReactDOM from "react-dom";
import { createStore, applyMiddleware, compose } from "redux";
import { Provider } from "react-redux";
import { composeWithDevTools } from "redux-devtools-extension";

import App from "./App";
import rootReducer from "./reducers";

const enhancer = compose(applyMiddleware());
const store = createStore(rootReducer, enhancer);

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

 

4.4. Component에서 redux 사용하기

import { useSelector, useDispatch } from "react-redux";
import { increseCount } from "reducers/count";

const dispatch = useDispatch();
const { count } = useSelector(state => state.counter);

const increse = () => {
    dispatch(increseCount());
};

const Counter = () => {
    return (
        <div>
            {count}
            <button onClick={increse}>증가</button>
        </div>
    );
};

export default Counter;

store에서 useDispatch, useSelector로 state와 함수를 가져와서 필요한 곳에 호출해주면 된다.

 

 

5. Redux 보완점

Redux의 함수는 무조건 동기적으로 데이터가 흘러간다. 하지만 웹은 비동기로 사용자 경험(UX)을 높이는 것이 중요하다. 그래서 나온 것이 redux-saga이다. redux와 redux-saga를 동시에 사용함으로써 비동기의 유연함을 같이 가져갈 수 있다. redux-saga에 대한 내용은 추후 다른 게시글에서 다루겠다.

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2025/04   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30
글 보관함