React-Redux 설명

React-Redux 설명

React-Redux란?


1. React 앱 + Redux


  • APP.js에서 꼭 렌더링한 App을 subscribe()를 해주어야 Redux를 구동할 수 있다.

React + Redux — 루트 리듀서 (여러 개의 리듀서 병합)

  • Redux의 스토어는 하나이지만, Reducer는 하나 이상 생성할 수 있다.
  • APP의 규모가 커지면 그 만큼 Reducer가 많아지게 된다. 이에 따라 멀티 Reducer를 관리하려면 하나의 루트 리듀서를 만들어 다수의 Reducer를 변합하여 사용한다.
  • 루트 리듀서는 conbineReducers()함수를 사용해 다수의 리듀서를 묶어서 관리할 수 있었다.
1
2
3
4
5
6
7
import { combineReducers } from 'redux';
import todosReducer from './reducers/todosReducer';
import counterReducer from './reducers/counterReducer';

const rootReducer = combineReducers({ todosReducer, counterReducer });

export default rootReducer;

2. React Redux


  • react-redux 패키지는 React에 맞게 Redux를 사용할 수 있도록 한다.

React-Redux - 설치

해당 코드를 사용하여 React-Redux 설치하여야 한다.

1
npm i react-redux

React-Redux - Provider, Connect 컴포넌트

  • Provider와 Connect는 React앱에 Redux의 효율적은 App 상태 관리 방법을 쉽게 사용할 수 있도록 관계를 형성해야한다.
  • 다음 사진과 같은 방식으로 React-Redux에 관한 작동 흐름이다.
    • Counter App은 React에서 가상 DOM으로 구성되어있다.
    • ReactDom.render에서 실제 DOM에 뿌려주게 된다.
    • Store에 있는 데이터를 모든 DOM에 뿌려주기 위해 Provider 즉 공급자로 각 DOM에 공급하게 됩니다.
    • Provider를 감싼 하위 컴포넌트에 Store를 공급할 수 있고 Connect를 사용하여 Store에 상태를 업데이트하기 위해 Connect에서는 상태 업데이트하기 위해 dispatch를 사용하여 업데이트하고 Action은 Reducer를 실행하기 위하여 보내는 역할을 한다.

React-Redux에 관한 작동 흐름

  • Provider

    • Provider는 포함된 모든 하위(자식, 자손) 컴포넌트에 Redux Store를 제공하는 컴포넌트이다.
    • <provider><App/>을 감싸게 되면 모든 컴폰너트에서 스토어에 접근해 상태 변경을 요청(dispatch)하거나, 구독(subscription)된 상태가 업데이트 되면 다시 렌더링 된다.
    1
    2
    3
    4
    5
    6
    ReactDom.render(
    <provider store={stpre}>
    <App />
    </provider>,
    document.getElementById('root')
    );
  • Connect

    • Connect는 컴포넌트를 스토어에 접근 가능하도록 연결하는 컴포넌트 이다.
    • Connect를 사용하면 컴포넌트에 일일이 Store 또는 상태(state), 디스패치(dispatch)를 직접 연결하지 않아도 된다.
    • Connect컴포넌트는 고차 컴포넌트(HOC)입니다. HOC가 하는 일은 기존 컴포넌트를 랩핑하고 추가 기능을 주입해 기준 컴포넌트의 기능을 확장한다.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    import { connect } from 'react-redux';
    const Component = () => {
    const { stateName } = this.props;
    return ();
    };

    // 다음과 같이 Reducer를 통해 Store에 있는 state를 변수로 가져올 수 있다.
    const mapStateToProps = state => ({
    stateName: state.stateReducer.stateName,
    });

    // 다음과 같이 Component를 connect로 감싸주어 사용가능
    export default connect(mapStateToProps)(Component);

    React Redux 패키지 — Connect 고차 컴포넌트의 mapStateToProps, mapDispatchToProps 설정

  • 좀더 자세한 설명

Redux Devtools — 상태 관리 시각화

  • Redux DevTools 설치 사이트 로 이동하여 다운로드 해주면 됩니다.
  • Chrome 검사창을 열어 Redux를 열어주면 Redux 변동사항 및 데이터가 넘어가는것을 시각화로 볼 수 있다.

3. React Redux Hooks


  • 다음과 같이 useSelector와 useDispatch를 사용할 수 있다.
    import { useSelector, useDispatch } from "react-redux";

React-Redux: UseSelector()

  • 이 Hook은 리덕스 스토어의 상태에 접근할 수 있다.
    const result: any = useSelector(selector: Function, equalityFn ?: Function)
    • 여기서 두번째 파라미터로 오는 equalityFun은 이전값과 다음값을 비교하여 true이면 랜더링하지 않고, false이면 리랜더한다. -UseSelectir() 최적화 방법 3가지 해당 사이트를 참고해주세요.

React-Redux: UseDispatch()

  • 이 훅은 기존에 props로 액션 생성 함수를 사용하는 것처럼 액션 객체를 dispatch해준다.
    const dispatch = useDispatch();
Author

YoungHea Kim

Posted on

2021-05-20

Updated on

2021-05-20

Licensed under