본문 바로가기
프로그래밍/개발 언어

Redux

by monicada 2022. 7. 6.
728x90

정의

  • 리액트 없이도 사용할 수 있는 상태 관리 라이브러리
  • Redux는 컴포넌트와 상태를 분리하는 패턴
  • 상태 변경 로직을 컴포넌트로부터 분리하면 표현에 집중한, 단순한 함수 컴포넌트로 만들 수 있게 함 

 

순서 상태 관리 

Action → Dispatch → Reducer → Store

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


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

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


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

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


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

import { createStore } from 'redux';

const store = createStore(rootReducer);

 

Redux 세 가지 원칙

1. single source of truth

동일한 데이터는 항상 같은 곳에서 가져오기, store에서 가져오기

2. state is read-only

상태는 읽기 전용, 상태를 직접 변경 어려움, action 객체가 있어야만 상태를 변경 가능 

3. changes are made with pure functions

변경은 순수함수로만 가능, reducer와 연결됨 

 

'프로그래밍 > 개발 언어' 카테고리의 다른 글

[React] 상태관리  (0) 2022.07.07
[React] Cmarket Redux  (0) 2022.07.06
React Custom Component  (0) 2022.07.04
[React] Custom Component  (0) 2022.07.04
JSON.stringify  (0) 2022.06.24

댓글