(SEB_FE) Section3 Unit4 Redux

PYM·2023년 4월 23일
0

(SEB_FE) SECTION3

목록 보기
12/22
post-thumbnail

상태 관리 라이브러리가 왜 필요한지 이해할 수 있다.
Redux에서 사용하는 Action, Dispatcher, Reducer 그리고 Store의 의미와 특징을 이해할 수 있다.
Redux의 3가지 원칙이 무엇이며, 주요 개념과 어떻게 연결되는지 이해할 수 있다.

🍎Redux

하위 컴포넌트에서만 쓰이는 상태를 최상위 컴포넌트에 위치시킬 경우, 아래와 같은 문제점이 등장하게 된다

  1. 해당 상태를 직접 사용하지 않는 최상위 컴포넌트, 컴포넌트1, 컴포넌트2도 상태 데이터를 가짐
  2. 상태 끌어올리기, Props 내려주기를 여러 번 거쳐야 함
  3. 애플리케이션이 복잡해질수록 데이터 흐름도 복잡해짐
  4. 컴포넌트 구조가 바뀐다면, 지금의 데이터 흐름을 완전히 바꿔야 할 수도 있음

상태 관리 라이브러리인 Redux는, 전역 상태를 관리할 수 있는 저장소인 Store를 제공함으로써 이 문제들을 해결해 준다

기존 React에서의 데이터 흐름과, Redux를 사용했을 때의 데이터 흐름을 비교해 보면, Redux를 사용했을 때의 데이터 흐름이 보다 더 깔끔해지는 것을 알 수 있다.

🍎Redux의 구조

Redux는 다음과 같은 순서로 상태를 관리한다.

  1. 상태가 변경되어야 하는 이벤트가 발생하면, 변경될 상태에 대한 정보가 담긴 Action 객체가 생성된다

  2. 이 Action 객체는 Dispatch 함수의 인자로 전달된다.

  3. Dispatch 함수는 Action 객체를 Reducer 함수로 전달해 준다.

  4. Reducer 함수는 Action 객체의 값을 확인하고, 그 값에 따라 전역 상태 저장소 Store의 상태를 변경한다.

  5. 상태가 변경되면, React는 화면을 다시 렌더링 합니다.

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

🍎Store

상태가 관리되는 오직 하나뿐인 저장소의 역할.
다른 말로, Redux 앱의 state가 저장되어 있는 공간

아래 코드와 같이 createStore 메서드를 활용해 Reducer를 연결해서 Store를 생성할 수 있다.

import { createStore } from 'redux';

const store = createStore(rootReducer);

🍒 전역 변수 저장소를 설정하는 방법

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

/* 1. react-redux에서 Provider를 불러와야 한다
 - Provider는 store를 손쉽게 사용할 수 있게 하는 컴포넌트
해당 컴포넌트를 불러온다음에, Store를 사용할 컴포넌트를 감싸준 후
Provider 컴포넌트의 props로 store를 설정해 주면 OK! */
import { Provider } from 'react-redux';

// 2. redux에서 createStore를 불러와야 한다
import { legacy_createStore as createStore } from 'redux';

import { createStore } from 'redux';

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

const reducer = () => {};

/* 4. 변수 store에 createStore 메서드를 통해 store를 만든 후, 
createStore에 인자로 Reducer 함수를 전달해준다. */
const store = createStore(reducer);

root.render(
/* 3. 전역 상태 저장소 store를 사용하기 위해서는 App 컴포넌트를
Provider로 감싸준 후 props로 변수 store를 전달해주여야 한다 */ 
  <Provider store={store}>
    <App />
  </Provider>
);

🍎Reducer

Dispatch에게서 전달받은 Action 객체의 type 값에 따라
상태를 변경시키는 순수 함수 (일반 함수 아님)

  • 이때, Reducer는 순수함수여야 한다.
    ➡ 외부 요인으로 인해 기대한 값이 아닌 엉뚱한 값으로 상태가 변경되는 일이 없어야 하기 때문!

🍒 Reducer 함수 인자

  • 첫번째 인자
    기존 state가 들어온다. 이때, default value를 꼭 설정해야 한다.
    그렇지 않으면 undefined가 할당되기 때문에 오류가 발생할 수 있다.

  • 두번째 인자
    action 객체가 들어오게 된다.

action 객체에서 정의한 type에 따라 새로운 state를 리턴하고,
새로운 state는 전역 변수 저장소 Store에 저장되게 되는 것!

import React from 'react';
import { createRoot } from 'react-dom/client';
import App from './App';
import { Provider } from 'react-redux';
import { legacy_createStore as createStore } from 'redux';
import { createStore } from 'redux';

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

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가 리턴하는 값이 새로운 상태가 될 것이다. 

// 2
const store = createStore(counterReducer);

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

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

import { combineReducers } from 'redux';

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

🍎Action

말 그대로 어떤 액션을 취할 것인지 정의해 놓은 객체로,
다음과 같은 형식으로 구성된다.

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

// payload가 필요한 경우
{ type: 'SET_NUMBER', payload: 5 }
  • type 은 필수로 지정을 해 주어야 한다.
    해당 Action 객체가 어떤 동작을 하는지 명시해 주는 역할을 하기 때문이며, 대문자와 Snake Case로 작성한다.
    여기에 필요에 따라 payload를 작성해 구체적인 값을 전달할 수 있다.

보통 Action을 직접 작성하기보다는 아래와 같이 Action 객체를 생성하는 함수(액션 생성자(Action Creator))를 만들어 사용하는 경우가 많다.

 // payload가 필요 없는 경우
const increase = () => {
  return {
    type: 'INCREASE'
  }
}

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

🍎Dispatch

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

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

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

Action 객체를 전달받은 Dispatch 함수는 Reducer를 호출한다.

Store, Reducer, Action, Dispatch 이 네가지 개념을
Redux Hooks을 사용해서 연결해 주자!

🍎Redux Hooks

Redux Hooks는 React-Redux에서 Redux를 사용할 때 활용할 수 있는 Hooks 메서드를 제공.
그중에서 크게 useSelector(), useDispatch() 이 두 가지의 메서드를 기억하면 OK!

🍒 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에 접근할 수 있게 해주는 메서드

// Redux Hooks 메서드는 'redux'가 아니라 'react-redux'에서 불러온다
import { useSelector } from 'react-redux'
const counter = useSelector(state => state)
console.log(counter) // 1

예시 코드 최종

App.js

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

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

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

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

index.js

import React from 'react';
import { createRoot } from 'react-dom/client';
import App from './App';
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;

// 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가 리턴하는 값이 새로운 상태가 됩니다.
};

const store = createStore(counterReducer);

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

🍎Redux의 세 가지 원칙

🍒 1. Single source of truth

동일한 데이터는 항상 같은 곳에서 가지고 와야 한다.
➡ Redux엔 데이터를 저장하는 Store란 단 하나뿐인 공간이 있음과 연결이 되는 원칙

🍒 2. State is read-only

상태는 읽기 전용이라는 뜻으로, React에서 상태갱신함수로만 상태를 변경할 수 있었던 것처럼, Redux의 상태도 직접 변경할 수 없음을 의미.
➡ Action 객체가 있어야만 상태를 변경할 수 있음과 연결되는 원칙

🍒 3. Changes are made with pure functions

변경은 순수함수로만 가능하다는 뜻으로, 상태가 엉뚱한 값으로 변경되는 일이 없도록 순수함수로 작성되어야 하는 Reducer와 연결되는 원칙입니다.

profile
목표는 "함께 일하고 싶은, 함께 일해서 좋은" Front-end 개발자

0개의 댓글