Redux

Song Haeun·2023년 2월 24일
0

redux는 깔끔한 데이터 흐름을 위해 사용된다.
상태의 위치를 최상위 컴포넌트가 아닌 병도의 공간에 배치해 데이터 흐름을 깔끔하게 해준다.

Redux의 상태 관리 순서

Action → Dispatch → Reducer → Store

  1. 상태가 변경되어야 하는 이벤트가 발생하면, 변경될 상태에 대한 정보가 담긴 Action 객체가 생성됩니다.
  2. 이 Action 객체는 Dispatch 함수의 인자로 전달됩니다.
  3. Dispatch 함수는 Action 객체를 Reducer 함수로 전달해줍니다.
    4.Reducer 함수는 Action 객체의 값을 확인하고, 그 값에 따라 전역 상태 저장소 Store의 상태를 변경합니다.
    5.상태가 변경되면, React는 화면을 다시 렌더링 합니다.

Redux

Store

createStore 메서드를 활용해 Reducer를 연결해서 Store를 생성

import { createStore } from 'redux';

const store = createStore(rootReducer);

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

Action

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

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

//Action
export const increase = () => {
  return {
    type: 'INCREASE',
  };
};
export const decrease = () => {
  return {
    type: 'DECREASE',
  };
};
export const setNumber = (num) => {
  return {
    type: 'SET_NUMBER',
    payload: num,
  };
};

//Reducer
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;
  }
  // Reducer가 리턴하는 값이 새로운 상태가 됩니다.
};
//Store 생성
const store = createStore(counterReducer);

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

Redux Hooks

Redux를 사용할 때 활용할 수 있는 Hooks 메서드를 제공한다.
대표적으로 useSelector(), useDispatch() 메서드가 있다.

useDispatch()

Action 객체를 Reducer로 전달해 주는 Dispatch 함수를 반환하는 메서드
Dispatch를 사용할 때 이 메서드를 사용해서 만든다.

import { useDispatch } from 'react-redux'

const dispatch = useDispatch()
dispatch( increase() )

dispatch( setNumber(5) )

useSelector()

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

import { useSelector } from 'react-redux'
const counter = useSelector(state => state)
//App.js

import React from 'react';
import './style.css';
//useDispatch useSelector 선언
import { useDispatch, useSelector } from 'react-redux';
//Action Creater 함수 불러오기
import { increase, decrease } from './index.js';
export default function App() {
  //실행값 변수에 저장해서 사용
  const dispatch = useDispatch();

  //Store에 저장된 모든 state담기
  const state = useSelector((state) => state);

  const plusNum = () => {
    //Action 객체를 Reducer함수로 전달
    dispatch(increase());
  };

  const minusNum = () => {
    //Action 객체를 Reducer함수로 전달
    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>
  );
}
profile
프론트엔드 개발하는 송하은입니다🐣

0개의 댓글