[React] ☂️Redux로 전역상태 관리🌬️

TATA·2023년 2월 24일
0

React

목록 보기
13/32

상위 컴포넌트의 state를 props를 통해 하위 컴포넌트에게 전달할 때
전달 횟수가 5회 이상으로 많다면, Props Drilling의 문제점이 발생 할 수 있다.

Props Drilling의 문제점?
코드의 가독성↓, 코드의 유지보수↑,
관여한 컴포넌트의 불필요한 리렌더링 발생
즉, 웹 성능에 악영향을 줄 수 있다.

❗️이를 해결하기 위해서는
- 컴포넌트와 관련된 state를 가능한 가까이 유지하는 방법과
상태관리 라이브러리를 사용하여 전역으로 저장하는 저장소에서
     직접 state를 꺼내 쓰는 방법이 있다.

상태관리 라이브터리 종류: Redux, Context api, Mobx, Recoil 등..


▷ Redux

Redux를 사용하면 컴포넌트와 상태를 분리할 수 있다.

❗️참고) Redux는 리액트의 하위 컴포넌트가 아니다.(Redux는 리액트 없이도 사용 가능한 상태 관리 라이브러리임)


☂️ Redux의 구조

⒈ 상태 변경 이벤트가 발생하면, 해당 정보가 담긴 Action 객체가 생성된다.
⒉ 이 Action 객체는 Dispatch 함수의 인자로 전달된다.
⒊ Dispatch 함수는 Action 객체를 Reducer 함수로 전달해 준다.
⒋ Reducer 함수는 Action 객체의 값을 확인하고,
     그 값에 따라 전역 상태 저장소 Store의 상태를 변경한다.
⒌ 상태가 변경되면, React는 화면을 다시 렌더링 한다.

즉, Redux에서는 Action → Dispatch → Reducer → Store 순서로 데이터가 단방향으로 흐르게 된다.

❗️Redux의 세 가지 원칙
- Single source of truth : 데이터를 저장하는 단 하나뿐인 공간 Store와의 연결이어야 한다.
- State is read-only : 상태는 읽기 전용이다.(Action객체가 있어야 상태 변경 가능)
- Changes are made with pure functions : 변경은 순수함수로만 가능하다.


🌬️ 설치하기

# redux 설치
npm install redux

# react-redux 설치
npm install react-redux

# redux-toolkit
# npm install @reduxjs/toolkit react-redux redux --save

🌬️ Store

상태가 관리되는 오직 하나뿐인 저장소의 역할을 한다.

// as => 변수명 바꾸기
import { legacy_createStore as createStore } from 'redux';

const store = createStore(rootReducer);

---------------
// 미들웨어 적용 & 모듈 설치 안하고 개발자 도구 적용
import { compose, legacy_createStore as createStore, applyMiddleware } from "redux";
import thunk from "redux-thunk";

const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({}) : compose;
const store = createStore(rootReducer, composeEnhancers(applyMiddleware(thunk)));

---------------
// 모듈 설치하고 개발자 도구 적용
// npm install --save @redux-devtools/extension
import { composeWithDevTools } from "@redux-devtools/extension";

const store = createStore(rootReducer, composeWithDevTools(applyMiddleware(thunk)));

🌬️ Reducer

Dispatch에게서 전달받은
Action 객체의 type 값에 따라서 상태를 변경시키는 함수이다.

const count = 1

// Reducer를 생성할 때에는 초기 상태를 인자로 요구합니다.
const counterReducer = (state = count, action) => {

  // Action 객체의 type 값에 따라 분기하는 switch 조건문입니다.
  switch (action.type) {

    //action === 'INCREASE'일 경우
    case 'INCREASE':
			return state + 1

    // action === 'DECREASE'일 경우
    case 'DECREASE':
			return state - 1

    // action === 'SET_NUMBER'일 경우
    case 'SET_NUMBER':
			return action.payload

    // 해당 되는 경우가 없을 땐 기존 상태를 그대로 리턴
    default:
      return state;
	}
}
// Reducer가 리턴하는 값이 새로운 상태가 됩니다.

만약 여러 개의 Reducer를 사용하는 경우,
Redux의 combineReducers 메서드를 사용해서
하나의 Reducer로 합쳐줄 수 있다.

import { combineReducers } from 'redux';

const rootReducer = combineReducers({
  counterReducer,
  anyReducer,
  ...
});
  
--------
import { useSelector } from "react-dom"
                                    
const state = useSelector((state) => state.counterReducer)

🌬️ Action

Action은 어떤 액션을 취할 것인지 정의해 놓은 객체이다.

❗️참고) type은 필수로 지정해 주어야 하며, 대문자와 Snake Case로 작성해야 한다.

/* - payload가 필요 없는 경우 */
{ type: 'INCREASE' }

/* - payload가 필요한 경우
     필요에 따라 payload를 작성하여 구체적인 값을 전달
     (payload란 액션의 실행에 필요한 임의의 데이터를 말한다.)*/
{ type: 'SET_NUMBER', payload: 5 }

----------------
/* Action을 직접 작성하기보다는 Action 객체를 생성하는 함수를 만들어 사용하는 경우가 많다.
   이러한 함수를 액션 생성자라고도 한다. */
  
// - payload가 필요 없는 경우
const increase = () => {
  return {
    type: 'INCREASE'
  }
}

// - payload가 필요한 경우
const setNumber = (num) => {
  return {
    type: 'SET_NUMBER',
    payload: num
  }
}

🌬️ Dispatch

Dispatch는 Reducer로 Action을 전달해주는 함수이다.
Dispatch의 전달인자로 Action 객체가 전달된다.

// Action 객체를 직접 작성하는 경우
dispatch( { type: 'INCREASE' } );
dispatch( { type: 'SET_NUMBER', payload: 5 } );

// 액션 생성자(Action Creator)를 사용하는 경우
dispatch( increase() );
dispatch( setNumber(5) );

☂️ Redux Hooks

React-Redux에서 Redux를 사용할 때 활용할 수 있는 Hooks 메서드를 제공한다.

🌬️ useDispatch

Action객체를 Reducer로 전달해 주는 Dispatch 함수를 반환하는 메서드이다.

import { useDispatch } from 'react-redux'

const dispatch = useDispatch()
dispatch( increase() )
console.log(counter) // 2

dispatch( setNumber(5) )
console.log(counter) // 5

🌬️ useSelector

컴포넌트와 state를 연결하여 Redux의 state에 접근할 수 있게 해주는 메서드이다.

import { useSelector } from 'react-redux'

const counter = useSelector((state) => state)

☂️ Redux 사용 예시

index.js

import React from 'react';
import { createRoot } from 'react-dom/client';
import App from './App';
/* Provider는 store를 손쉽게 사용할 수 있게 하는 컴포넌트이다 */
import { Provider } from 'react-redux';
import { legacy_createStore as createStore } from 'redux';

const rootElement = document.getElementById('root');
const root = createRoot(rootElement);

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

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

const count = 1;

const counterReducer = (state = count, action) => {
  switch (action.type) {
    case 'INCREASE':
      return state + 1;

    case 'DECREASE':
      return state - 1;

    case 'SET_NUMBER':
      return action.payload;

    default:
      return state;
  }
};

const store = createStore(counterReducer);

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

app.js

import React from 'react';
import './style.css';

import { useDispatch, useSelector } from 'react-redux';
import { increase, decrease } from './index.js';

export default function App() {
  const state = useSelector((state) => state)
  const dispatch = useDispatch();

  const plusNum = () => {
    dispatch(increase());
  };

  const minusNum = () => {
    dispatch(decrease());
  };

  return (
    <div className="container">
      <h1>{`Count: ${state}`}</h1>
      <div>
        <button className="plusBtn" onClick={plusNum}>
          +
        </button>
        <button className="minusBtn" onClick={minusNum}>
          -
        </button>
      </div>
    </div>
  );
}

참고

Redux 코드를 역할별로 나누어 관리할 수도 있다.




🔮 Redux Toolkit 사용법 보러가기
👉 Redux 공식문서
👉 React-Redux 공식문서
👉 robinwieruch 블로그: Redux
👉 FLUX 패턴 공식 문서
👉 (공식문서)복잡한 Redux의 코드를 개선하는 데 도움이 되는 Redux Toolkit
👉 (공식문서)Redux Toolkit의 createAsyncThunk를 활용하여 비동기 코드 처리 방법
👉 (공식문서)Redux 예제들

profile
🐾

0개의 댓글