Redux [전역 상태 관리]

hyo·2023년 3월 20일
0

상태 관리

목록 보기
1/3
post-thumbnail

Redux

Redux의 구조

1. 상태가 변경되어야 하는 이벤트 발생

2. 변경될 상태에 대한 정보가 담긴 Action 객체가 생성됨.

3. 이 Action 객체는 Dispatch 함수의 인자로 전달됨.

4. Dispatch 함수는 Action 객체를 Reducer 함수로 전달해줌.

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

6. 상태가 변경되면, React는 화면을 다시 렌더링 함.

즉 , Redux에서는 Action -> Dispatch -> Reducer -> Store 순서로 데이터가 단방향으로 흐른다.


Redux의 각각의 개념

Store

react-redux를 설치하고 난 뒤,
Provider 컴포넌트를 불러온다. ->
import {Provider} from 'react-redux'

Provider는 store를 손쉽게 사용할 수 있게 하는 컴포넌트이다.

Provider 컴포넌트를 불러온 다음, Store를 사용할 컴포넌트를 감싸준다.
Provider 컴포넌트의 props로 store를 설정해준다.
전역 상태 저장소 store를 사용하기 위해서는 App 컴포넌트를 Provider로 감싸준 후 props로 변수 store를 전달해주여야 한다.
root.render(
   <Provider store={store}>
     <App />
   </Provider>  
)
redux에서 createStore를 불러와야 한다.
import { legacy_createStore as createStore } from 'redux';
변수 store에 createStore 매서드를 통해 store를 만들어 준다.
createStore에 인자로 Reducer 함수를 전달해 준다.
const store = createStore(리듀서함수) // Reducer함수를 이런식으로 넣어준다.

Reducer

ReducerDispatch에게서 전달받은 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_NUM'일 경우
    case 'SET_NUM':
			return action.payload

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

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

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

const count = 1

const counterReducer = (state = count, action) => {
  switch (action.type) {
    case 'INCREASE':
			return state + 1
    case 'DECREASE':
			return state - 1
    case 'SET_NUM':
			return action.payload
    default:
      return state;
	}
}

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

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

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

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

보통 Action을 직접 작성하기보다는 Action 객체를 생성하는 함수를 만들어 사용하는 경우가 많다.

이러한 함수를 액션 생성자(Action Creator)라고도 한다.

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

// payload가 필요한 경우
const setNum = (num) => {
  return {
    type: 'SET_NUM',
    payload: num
  }
}
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'}
}

export const setNumber = (num) => {
  return { type: 'SET_NUMBER', payload: num}
}

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

Dispatch

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

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

// 액션 생성자(Action Creator)를 사용하는 경우
dispatch( increase() );
dispatch( setNum(2) );
  • Action 객체를 전달받은 Dispatch 함수는 Reducer를 호출한다.

여기까지 Store, Reducer, Action, Dispatch 개념들을 학습해보았다.

이제 이 개념들을 연견시켜 주어야 하는데, Redux Hooks를 사용하면 된다.


Redux Hooks

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

useDispatch()

useDispatch() 는 Action 객체를 Reducer로 전달해 주는 Dispatch 함수를 반환하는 메서드이다.
위에서 Dispatch를 설명할 때 사용한 dispatch 함수도 useDispatch()를 사용해서 만든 것이다.

import { useDispatch } from 'react-redux'

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

dispatch( setNum(10) )
console.log(counter) // 10

useSelector()

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

import { useSelector } from 'react-redux'
const counter = useSelector(state => state)
console.log(counter) // 1

// 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',
  };
};

export const setNumber = (num) => {
  return {type: 'SET_NUMBER', payload: num}
}

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';
// 1
import { useDispatch, useSelector } from 'react-redux';
import { increase, decrease, setNumber } from './index.js';

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

  const state = useSelector((state) => state);

  console.log(state); // 전역 상태에 있는 state를 읽음.
  

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

  const minusNum = () => {
    dispatch(decrease());
  };
  const setNum = (num) => {
    dispatch(setNumber(num))
  }

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

리팩토링

위의 코드구조는 index.js 파일에 action, reducer,store를 다 적었다.
한 파일에 다양한 기능의 코드들을 작성하는 것은 좋지않고 가독성이 떨어진다.

코드 역할 별로 리팩토링을 해보자.

actions.js

export const INCREASE = 'INCREASE';
export const DECREASE = 'DECREASE';
export const SET_NUMBER = 'SET_NUMBER';

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

export const decrease = () => {
  return {
    type: DECREASE
  }
}
export const setNumber = (n) => {
  return {
    type: SET_NUMBER,
    payload: n,
  }
}

reducers.js

import { initialState } from './initialState.js';
import { INCREASE, DECREASE, SET_NUMBER, increase, decrease } from '../Actions';

export const counterReducer = (state = initialState, action) => {
  switch(action.type){
    case INCREASE:
      return state + 1;
    case DECREASE:
      return state - 1;
    case SET_NUMBER:
      return action.payload;
    default:
      return state;
  }
}

initialState.js

export const initialState = 1;

store.js

import { legacy_createStore as createStore } from 'redux';
import { counterReducer } from '../Reducers';

export const store = createStore(counterReducer);

App.js

import React from 'react';
import './style.css';
import { useSelector, useDispatch } from 'react-redux';
import { increase, decrease, setNumber } from './Actions';

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

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

  const minusNum = () => {
    dispatch(decrease());
  };
  const setNum = (n) => {
    dispatch(setNumber(n));
  }

  return (
    <div className="container">
      <h1>{`Count: ${state}`}</h1>
      <div>
        <button className="plusBtn" onClick={plusNum}>
          +
        </button>
        <button className="minusBtn" onClick={minusNum}>
          -
        </button>
        <button className="minusBtn" onClick={() => {
          setNum(1)
        }}>
          초기화
        </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 { store } from './Store';

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

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
개발 재밌다

0개의 댓글