[React] Redux

Hannahhh·2022년 9월 1일
0

React

목록 보기
18/30

🔍 Redux


React 없이도 사용할 수 있는 상태 관리 라이브러리로, 전역 state를 관리하는 저장소(Store)를 제공하여 props drilling 이슈를 해결해준다.


Redux를 사용하지 않은 경우와 Redux를 사용한 경우의 데이터 흐름을 비교해보면, 후자의 경우가 더 단순하고 깔끔하다는 것을 알 수 있다.



👀 Redux의 3가지 원칙


1. Single source of truth

Store와 연결되는 원칙으로, 동일한 데이터의 출처는 항상 같아야 한다.


2. State is read-only

state를 직접 변경할 수 없고, Action 객체를 통해서 변경할 수 있다.


3. Changes are made with pure functions

Reducer와 연결되는 원칙으로, 변경은 순수함수로 작성한 코드에서만 가능하다.




👀 Redux의 구조



Redux는 다음과 같이 작동한다.

  1. state 변경 이벤트 발생 시, 변경될 state에 대한 정보가 담긴 Action 객체가 생성된다.

  2. Action객체가 Dispatch 함수의 인자로 전달되고, Dispatch 함수는 Action 객체를 Reducer 함수로 전달한다.

  3. Reducer 함수는 Action 객체의 값을 확인하고, 값에 따라 전역 state 저장소(Store)의 state를 변경한다.

  4. state 변경 후, React는 view를 다시 렌더링한다.



✔ Store


전역 state를 관리하는 저장소로, createStore 메서드를 사용하여 Reducer를 연결해서 생성할 수 있다.

아래는 Store를 생성 및 설정하는 예시 코드이다.


// index.js

import React from 'react';
import { createRoot } from 'react-dom/client';
import App from './App';

// 1. store를 쉽게 사용할 수 있는 provider 컴포넌트 import
import { Provider } from 'react-redux';

// 2. redux에서 createStore import
import { legacy_createStore as createStore } from 'redux';

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

const reducer = () => {};

// 3.변수 store에 createStore 메서드를 통해 store를 만들어준 후, 인자로 위의 reducer 함수를 전달해야 한다.
const store = createStore(reducer);

// 4. store를 사용하기 위해서 App 컴포넌트를 Provider 컴포넌트로 감싸준 후, props로 store를 전달해야한다.
root.render(
  <Provider store={store}>
  <App />
  </Provider>
);



✔ Reducer


Dispatch 함수로 부터 전달받은 Action 객체의 type값을 확인하고, 값에 따라 Store의 state를 변경하는 함수이다.

이 때 Reducer는 순수함수여야 한다.


// index.js

// 첫 번째 인자에는 기존 state(default value)
// 두 번째 인자에는 action 객체

import React from 'react';
import { createRoot } from 'react-dom/client';
import App from './App';

// store를 쉽게 사용할 수 있는 provider 컴포넌트 import
import { Provider } from 'react-redux';

// redux에서 createStore import
import { legacy_createStore as createStore } from 'redux';

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

const count = 1

// Reducer 함수 시작
// Reducer를 생성할 때에는 초기 상태를 인자로 요구한다.

// 리듀서가 처음 호출될 때, state값은 undefined이다. 
// 따라서, state의 초깃값을 지정해서 액션이 발생하기 전에 이 케이스에 대해 처리해줘야 한다.
// 만약 초깃값을 설정해주지 않을 시 오류가 발생한다.
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 함수 끝

// 변수 store에 createStore 메서드를 통해 store를 만들어준 후, 인자로 위의 reducer 함수를 전달해야 한다.
const store = createStore(counterReducer);

// store를 사용하기 위해서 App 컴포넌트를 Provider 컴포넌트로 감싸준 후, props로 store를 전달해야한다.
root.render(
  <Provider store={store}>
  <App />
  </Provider>
);


여러 개의 Reducer를 사용하는 경우 combineReducer 메서드를 사용해 합쳐줄 수 있다.

import { combineReducers } from 'redux';

const rootReducer = combineReducers({
  counterReducer,
  anyReducer,
  ...
});



✔ Action


state를 어떻게 변경할 지 정의해놓은 객체이다.

Dispatch 함수를 통해 Reducer 함수 두 번째 인자로 전달되며,
Action 객체 안의 type을 필수로 지정해야한다.(Snake Case로 작성), 필요하다면 payload를 작성해 구체적인 값을 전달할 수 있다.

지정한 type에 따라 Reducer 함수에서 새로운 state를 리턴한다.


import React from 'react';
import { createRoot } from 'react-dom/client';
import App from './App';

// store를 쉽게 사용할 수 있는 provider 컴포넌트 import
import { Provider } from 'react-redux';

// redux에서 createStore import
import { legacy_createStore as createStore } from 'redux';

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

// Action creator 코드 시작
// 1. Action Creator 함수 increase
// payload가 필요 없는 경우
export const increase = () => {
  return {
    type: 'INCREASE'
  }
}

// 2. Action Creator 함수 decrease
// payload가 필요 없는 경우
export const decrease = () => {
  return {
    type: 'DECREASE'
  }
}
// Action creator 코드 끝

const count = 1

// Reducer 함수 시작
// 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 함수 끝

// 변수 store에 createStore 메서드를 통해 store를 만들어준 후, 인자로 위의 reducer 함수를 전달해야 한다.
const store = createStore(counterReducer);

// store를 사용하기 위해서 App 컴포넌트를 Provider 컴포넌트로 감싸준 후, props로 store를 전달해야한다.
root.render(
  <Provider store={store}>
  <App />
  </Provider>
);



✔ Dispatch


전달받은 Action 객체를 Reducer 함수로 전달해주는 함수로, 전달인자로 Action 객체가 전달된다. 이때, Action 객체를 전달받은 Dispatch함수는 Ruducer를 호출한다.

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

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




✔ Redux Hooks


✔ useDispatch()


바로 위의 Dispatch 함수를 return하는 메서드이다.


// App.js

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

// 1. react-redux에서 useDispatch를 불러온다.
import { useDispatch } from 'react-redux';

// 2. Action Creater 함수 increase, decrease를 불러온다.
import { increase,decrease } from './index.js';

export default function App() {
  // 3. useDispatch의 실행 값를 변수에 저장해서 dispatch 함수 사용
  const dispatch = useDispatch()
  // console.log(dispatch);

  const plusNum = () => {
    // 4. 이벤트 핸들러 안에서 dispatch를 통해 action 객체를 Reducer 함수로 전달한다.
    dispatch( increase() );
    // console.log(counter) // 2
  };

  const minusNum = () => {
    // 5. 이벤트 핸들러 안에서 dispatch를 통해 action 객체를 Reducer 함수로 전달한다.
    dispatch( decrease() );
    // console.log(counter) // 0
  };

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



✔ useSelector()


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


// App.js

import React from 'react';
import './style.css';
// 1. react-redux에서 useSelector를 불러온다.
import { useDispatch, useSelector } from 'react-redux';

import { increase, decrease } from './index.js';

export default function App() {
  const dispatch = useDispatch();
  // 2. useSelector의 콜백 함수의 인자에 Store에 저장된 모든 state가 담긴다. 
  const state = useSelector((state) => state);
  console.log(state); // 1

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

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

  return (
    <div className="container">
      {/* 3. state를 화면에 출력 */}
      <h1>{`Count: ${state}`}</h1>
      <div>
        <button className="plusBtn" onClick={plusNum}>
          +
        </button>
        <button className="minusBtn" onClick={minusNum}>
          -
        </button>
      </div>
    </div>
  );
}




👀 Flux pattern


웹 애플리케이션을 구축하는 데 사용하는 애플리케이션 아키텍처로, 단방향 데이터 흐름이다.

모든 데이터는 Dispather를 통해 중앙 허브로 흐르는데 Redux와 유사한 구조를 가지고 있으며, 다음과 같이 작동한다.

  1. Action 발생 시, Action creator가 type과 payload를 Dispatcher에게 전달한다.

  2. Action을 전달받은 Dispatcher는 Action을 Store에 전달한다.

  3. Dispatcher로부터 Action을 전달받은 Store는 Action의 값을 확인하고 state를 변경한다.

  4. state 변경 후, React는 view를 다시 렌더링한다.




위의 이미지를 보면, Flux와 Redux의 차이를 확인해볼 수 있는데, 정리하면 아래와 같다.

ReduxFlux
Dispatcher 유무X
Reducer가 dispatcher와 store의 기능을 함
O
singleton dispatcher
Store 개수1개
one source of truth
복수
multiple source of truth
state 변경 가능 여부XO




Reference:

0개의 댓글