happyso
study with happyso
happyso
전체 방문자
오늘
어제
  • 분류 전체보기 (302)
    • GIT (3)
    • 컴퓨터 기본 개념 (29)
    • 알고리즘 (125)
      • 알고리즘 문제 (115)
      • 알고리즘 개념 (10)
    • Go (2)
    • 클라우드 (54)
      • DevOps (4)
      • Kubernetes(쿠버네티스) (33)
      • AWS (6)
      • CKA (8)
    • 리눅스(Linux) (18)
      • 컨테이너(Container) (8)
    • Front (22)
      • JavaScript (2)
      • React (20)
    • Python (21)
      • Python 웹 크롤링 (11)
      • Django (7)
      • MachineLearning (3)
    • 데이터베이스 (6)
      • MariaDB (2)
      • MongoDB (4)
    • C언어 (5)
    • Trouble Shooting (2)
    • 네트워크 (8)
      • CCNA (5)
    • 보안 (1)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • Patch
  • kubernetes
  • replace
  • apply
  • 15
  • 18
  • edit

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
happyso

study with happyso

[React] 리덕스 라이브러리
Front/React

[React] 리덕스 라이브러리

2021. 1. 14. 16:48
  • 가장 많이 사용하는 리액트 관련 상태 라이브러리
  • 컴포넌트의 상태 업데이트 관련 로직을 다른 파일로 분리시켜 더욱 효율적으로 관리할 수 있다.
  • 컴포넌트끼리 똑같은 상태를 공유해야 할 때 여러 컴포넌트를 거치지 않고 손쉽게 상태 값을 전달하거나 업데이트할 수 있다.
  • 전역 상태를 관리할 때 효과적
  • 미들웨어 기능을 제공하여 비동기 작업을 훨씬 효율적으로 관리할 수 있다.

1. 개념

1.1. 액션

  • 상태에 어떠한 변화가 필요하면 액션이란 것이 발생
  • 다음과 같은 형식으로 이루어져 있다.
{
	type: 'TOGGLE_VALUE'
}
  • 액션 객체는 type 필드를 반드시 가지고 있어야 한다.
    • 이 값을 액션의 이름이라 생각하면 된다.
  • 그 외의 값들은 나중에 상태 업데이트를 할 때 참고해야 할 값이며, 작성자 마음대로 넣을 수 있다.
{
   type: 'ADD_TODO',
   data: {
      id: 1,
      text: '리덕스 배우기'
    }
}

{
   type: 'CHANGE_INPUT',
   text: '안녕하세요'
}

 

 

1.2. 액션 생성 함수

  • 액션 객체를 만들어 주는 함수
function addTodo(data) {
	return {
       type: 'ADD_TODO',
       data
    };
}

// 화살표 함수로도 만들 수 있습니다.
const changeInput = text => ({
   type: 'CHANGE_INPUT',
   text
});
  • 어떤 변화를 일으켜야 할 때마다 액션 객체를 만들어야 하는데 매번 액션 객체를 직접 작성하기 번거로울 수 있고, 만드는 과정에서 실수로 전보를 놓칠 수 있다.
  • 이러한 일들을 방지하기 위해 함수로 만들어 관리한다.

 

1.3. 리듀서

  • 변화를 일으키는 함수
  • 액션을 만들어서 발생시키면 리듀서가 현재 상태와 전달받은 액션 객체를 파라미터로 받아온다. 그리고 두 값을 참고하여 새로운 상태를 만들어 반환해준다.
const initialState = {
   counter: 1
};
function reducer(state = initialState, action) {
   switch (action.type) {
      case INCREMENT:
         return {
            counter: state.counter + 1
         };
      default:
         return state;
   }
}

 

1.4. 스토어

  • 프로젝트에 리덕스를 적용하기 위해 스토어를 만든다.
  • 한 개의 프로젝트는 단 하나의 스토어만 가질 수 있다.
  • 스토어 안에는 현재 애플리케이션 상태와 리듀서가 들어가 있으며, 그 외에 몇가지 중요한 내장 함수를 지닌다.

 

1.5. 디스패치

  • 스토어 내장 함수 중 하나
  • 액션을 발생시키는 것이다.
  • dispatch(action) 과 같은 형태로 액션 객체를 파라미터로 넣어서 호출
  • 이 함수가 호출되면 스토어는 리듀서 함수를 실행시켜서 새로운 상태를 만들어준다.

 

1.6. 구독

  • 스토어 내장 함수 중 하나
  • subscribe 함수 안에 리스너 함수를 파라미터로 넣어서 호출해주면, 이 리스너 함수가 액션이 디스패치되어 상태가 업데이트될 때마다 호출된다.
const listener = () => {
   console.log('상태가 없데이트됨')
}
const ubsubscribe = store.subscribe(listener);

unsubscribe(); // 추후 구독을 비활성화할 때 함수를 호출

 

2. 리액트 없이 쓰는 리덕스

  • 리덕스는 리액트에 종속되는 라이브러리가 아니다.
    • 실제 다른 UI 라이브러리/프레임워크와 함께 사용할 수 있다.(예: angular-redux, ember-redux, Vue)
  • 리덕스는 바닐라 자바스크립트와 함께 사용할 수 있다.
    • 바닐라 자바스크립트 : 라이브러니나 프레임워크 없이 사용하는 순수 자바스크립트 그 자체
  • 바닐라 자바스크립트 환경헤서 리덕스를 사용하여 리덕스의 핵심 기능과 작동 원리를 이해해보겠다.

 

2.1. Parcel로 프로젝트 만들기

  • 프로젝트를 구성하기 위해 Parcel 이라는 도구를 사용하겠다. 이 도구를 사용하면 아주 쉽고 빠르게 웹 애플리케이션 프로젝트를 구성할 수 있다.
$ yarn global add parcel-bundler
// yarn global이 잘 설치되지 않는다면 npm install -g parcel-bundler를 해 보세요

$ mkdir vanila-redux
$ cd vanila-redux
$ yarn init -y     // package.json 파일을 생성합니다.

[index.html]

<html>
    <body>
        <div>바닐라 자바스크립트</div>
        <script src="./index.js"></script>
    </body>
</html>

 

[index.js]

console.log('hello parcel')
  • 다 작성한 후 다음 명령어를 실행하면 개발용 서버가 실행된다.
$ parcel index.html

[결과]

  • 다음으로 yarn을 사용하여 리덕스 모듈을 설치하세요
$ yarn add redux

 

 

2.2. 간단한 UI 구성하기

 

[index.css]

.toggle {
    border: 2px solid black;
    width: 64px;
    height: 64px;
    border-radius: 32px;
    box-sizing: border-box;
}

.toggle.active {
    background: yellow;
}

 

[index.html]

<html>
    <head>
        <link rel="stylesheet" type="text/css" href="index.css" />
    </head>
    <body>
        <div class="toggle"></div>
        <hr />
        <h1>0</h1>
        <button id="increase">+1</button>
        <button id="decrease">-1</button>
        <script src="./index.js"></script>
    </body>
</html>

 

[결과]

 

2.3. DOM 레퍼런스 만들기

  • 이번 프로젝트에서는 UI를 관리할 때 별도의 라이브러리를 사용하지 않기 때문에 DOM을 직접 수정해 주어야 한다.
  • 자바스크립트 파일 상단에 수정할 DOM노드를 가리키는 값을 미리 선언해 준다.

[index.js]

const divToggle = document.querySelector('.toggle');
const counter = document.querySelector('h1');
const btnIncrease = document.querySelector('#increase');
const btnDecrease = document.querySelector('#decrease');

 

2.4. 액션 타입과 액션 생성 함수 정의

  • 프로젝트 상태에 변화를 일으키는 것을 액션이라 한다.
  • 먼저 액션 이름을 정의해 주겠다.
    • 액션 이름은 문자열 형태로, 주로 대문자로 작성하며 이름은 고유해야한다.

[index.js]

const divToggle = document.querySelector('.toggle');
const counter = document.querySelector('h1');
const btnIncrease = document.querySelector('#increase');
const btnDecrease = document.querySelector('#decrease');

const TOGGLE_SWITCH = 'TOGGLE_SWITCH';
const INCREASE = 'INCREASE';
const DECREASE = 'DECREASE';

 

다음으로 이 액션 이름을 사용하여 액션 객체를 만드는 액션 생성 함수를 작성해준다.

액션객체는 type을 반드시 갖고 있어야 하며, 그 외에 추후 상태를 업데이트할 때 참고하고 싶은 값은 마음대로 넣을 수 있다.

 

[index.js]

const divToggle = document.querySelector('.toggle');
const counter = document.querySelector('h1');
const btnIncrease = document.querySelector('#increase');
const btnDecrease = document.querySelector('#decrease');

const TOGGLE_SWITCH = 'TOGGLE_SWITCH';
const INCREASE = 'INCREASE';
const DECREASE = 'DECREASE';

const toggleSwitch = () => ({ type : TOGGLE_SWITCH });
const increase = difference => ({ type : INCREASE, difference });
const decrease = () => ({ type : DECREASE });

 

2.5. 초깃값 설정

  • 이 프로젝트에서 사용할 초깃값을 정의해 주겠다.
  • 초깃값의 형태는 자유이다.(숫자, 문자, 객체)

[index.js]

const divToggle = document.querySelector('.toggle');
const counter = document.querySelector('h1');
const btnIncrease = document.querySelector('#increase');
const btnDecrease = document.querySelector('#decrease');

const TOGGLE_SWITCH = 'TOGGLE_SWITCH';
const INCREASE = 'INCREASE';
const DECREASE = 'DECREASE';

const toggleSwitch = () => ({ type : TOGGLE_SWITCH });
const increase = difference => ({ type : INCREASE, difference });
const decrease = () => ({ type : DECREASE });

const initialState = {
    toggle: false,
    counter: 0
}

 

2.6. 리듀서 함수 정의

  • 리듀서는 변화를 일으키는 함수
  • 함수의 파라미터로는 state와 action 값을 받아온다.

[index.js]

const divToggle = document.querySelector('.toggle');
const counter = document.querySelector('h1');
const btnIncrease = document.querySelector('#increase');
const btnDecrease = document.querySelector('#decrease');

const TOGGLE_SWITCH = 'TOGGLE_SWITCH';
const INCREASE = 'INCREASE';
const DECREASE = 'DECREASE';

const toggleSwitch = () => ({ type : TOGGLE_SWITCH });
const increase = difference => ({ type : INCREASE, difference });
const decrease = () => ({ type : DECREASE });

const initialState = {
    toggle: false,
    counter: 0
}

// state가 undefined일 때는 initialState를 기본값으로 사용
function reducer(state = initialState, action) {
    // action.type에 따라 다른 작업을 처리함
    switch (action.type) {
        case TOGGLE_SWITCH:
            return {
                ...state, //불변성 유지를 해 주어야 한다.
                toggle: !state.toggle
            };
        case INCREASE:
            return {
                ...state,
                counter: state.counter + action.difference
            };
        case DECREASE:
            return {
                ...state,
                counter: state.counter - 1
            };
        default:
            return state
    }
}
  • 리듀서 함수가 맨 처음 호출될 때는 state값이 undefined이다.
    • 해당 값이 undefined로 주어졌을 때는 initialState를 기본값으로 설정하기 위해 함수의 파라미터 쪽에 기본값이 설정되어 있다.
  • 리듀서에서는 상태의 불변성을 유지하면서 데이터에 변화를 일으켜 주어야 한다.
    • 이 작업을 할 때 spread 연산자 (...) 를 사용하면 편하다.
    • 단 객체의 구조가 복잡해지면 (예: object.something.inside.value) spread 연산자로 불변성을 관리하며 업데이트 하는 것이 굉장히 번거로울 수 있고 코드의 가독성도 나빠지기 때문에 리덕스의 상태는 최대한 깊지 않은 구조로 진행하는 것이 좋다.
  • 객체의 구조가 복잡해지거나 배열도 함께 다루는 경우 immer 라이브러리를 사용하면 좀 더 쉽게 리듀서를 작성할 수 있다.

 

2.7. 스토어 만들기

  • 스토어를 만들 때는 createStore 함수를 사용한다.
  • 이 함수를 사용하려면 코드 상단에 import 구문을 넣어 리덕스에서 해당 함수를 불러와야 하고, 함수의 파라미터에는 리듀서 함수를 넣어주어야 한다.

[index.js]

import { createStore } from 'redux';

const divToggle = document.querySelector('.toggle');
const counter = document.querySelector('h1');
const btnIncrease = document.querySelector('#increase');
const btnDecrease = document.querySelector('#decrease');

const TOGGLE_SWITCH = 'TOGGLE_SWITCH';
const INCREASE = 'INCREASE';
const DECREASE = 'DECREASE';

const toggleSwitch = () => ({ type : TOGGLE_SWITCH });
const increase = difference => ({ type : INCREASE, difference });
const decrease = () => ({ type : DECREASE });

const initialState = {
    toggle: false,
    counter: 0
}

// state가 undefined일 때는 initialState를 기본값으로 사용
function reducer(state = initialState, action) {
    // action.type에 따라 다른 작업을 처리함
    switch (action.type) {
        case TOGGLE_SWITCH:
            return {
                ...state, //불변성 유지를 해 주어야 한다.
                toggle: !state.toggle
            };
        case INCREASE:
            return {
                ...state,
                counter: state.counter + action.difference
            };
        case DECREASE:
            return {
                ...state,
                counter: state.counter - 1
            };
        default:
            return state
    }
}

const store = createStore(reducer)

 

 

2.8. render 함수 만들기

  • 상태가 업데이트될 때마다 호츨되며, 리액트의 render 함수와는 다르게 이미 html을 사용하여 만들어진 UI의 속성을 상태에 따라 변경해준다.

 

[index.js]

import { createStore } from 'redux';

const divToggle = document.querySelector('.toggle');
const counter = document.querySelector('h1');
const btnIncrease = document.querySelector('#increase');
const btnDecrease = document.querySelector('#decrease');

const TOGGLE_SWITCH = 'TOGGLE_SWITCH';
const INCREASE = 'INCREASE';
const DECREASE = 'DECREASE';

const toggleSwitch = () => ({ type : TOGGLE_SWITCH });
const increase = difference => ({ type : INCREASE, difference });
const decrease = () => ({ type : DECREASE });

const initialState = {
    toggle: false,
    counter: 0
}

// state가 undefined일 때는 initialState를 기본값으로 사용
function reducer(state = initialState, action) {
    // action.type에 따라 다른 작업을 처리함
    switch (action.type) {
        case TOGGLE_SWITCH:
            return {
                ...state, //불변성 유지를 해 주어야 한다.
                toggle: !state.toggle
            };
        case INCREASE:
            return {
                ...state,
                counter: state.counter + action.difference
            };
        case DECREASE:
            return {
                ...state,
                counter: state.counter - 1
            };
        default:
            return state
    }
}

const store = createStore(reducer)

const render = () => {
    const state = store.getState(); // 현재 상태를 불러온다.
    // 토글 처리
    if (state.toggle) {
        divToggle.classList.add('active');
    } else {
        divToggle.classList.remove('active')
    }
    // 카운터 처리
    counter.innerText = state.counter;
};

render()

 

2.9. 구독하기

  • 이제 스토어의 상태가 바뀔 때마다 방금 만든 render 함수가 호출되도록 할 것이다.
    • 이 작업은 스토어의 내장 함수 subscribe를 사용하여 수항할 수 있다.
  • subscribe 함수의 파라미터로는 함수 형태의 값을 전달해 준다.
    • 이렇게 전달된 함수는 추후 액션이 발생하여 상태가 업데이트될 때마다 호출된다.

[예시 코드]

const listener = () => {
   console.log('상태가 업데이트됨')
}
const unsubscribe = store.subscribe(listener);

unsubscribe(); // 추후 구독을 비활성화할 때 함수를 호출

 

  • 이번 프로젝트에서는 subscribe 함수를 직접 사용하지만, 추후 리액트 프로젝트에서 리덕스를 사용할 때는 이 함수를 직접 사용하지 않을 것이다.
    • 왜냐하면 컴포넌트에서 리덕스 상태를 조회하는 과정에서 react-redux라는 라이브러리가 이 작접을 대신해 주기 때문이다.
  • 이제 상태가 업데이트 될 때마다 render함수를 호출하도록 코드를 작성해보자

[index.js]

import { createStore } from 'redux';

const divToggle = document.querySelector('.toggle');
const counter = document.querySelector('h1');
const btnIncrease = document.querySelector('#increase');
const btnDecrease = document.querySelector('#decrease');

const TOGGLE_SWITCH = 'TOGGLE_SWITCH';
const INCREASE = 'INCREASE';
const DECREASE = 'DECREASE';

const toggleSwitch = () => ({ type : TOGGLE_SWITCH });
const increase = difference => ({ type : INCREASE, difference });
const decrease = () => ({ type : DECREASE });

const initialState = {
    toggle: false,
    counter: 0
}

// state가 undefined일 때는 initialState를 기본값으로 사용
function reducer(state = initialState, action) {
    // action.type에 따라 다른 작업을 처리함
    switch (action.type) {
        case TOGGLE_SWITCH:
            return {
                ...state, //불변성 유지를 해 주어야 한다.
                toggle: !state.toggle
            };
        case INCREASE:
            return {
                ...state,
                counter: state.counter + action.difference
            };
        case DECREASE:
            return {
                ...state,
                counter: state.counter - 1
            };
        default:
            return state
    }
}

const store = createStore(reducer)

const render = () => {
    const state = store.getState(); // 현재 상태를 불러온다.
    // 토글 처리
    if (state.toggle) {
        divToggle.classList.add('active');
    } else {
        divToggle.classList.remove('active')
    }
    // 카운터 처리
    counter.innerText = state.counter;
};

render()
store.subscribe(render)

 

 

2.10. 액션 발생시키기

  • 액션을 발생시키는 것을 디스패치라고 한다.
    • 스토어의 내장 함수 dispatch를 사용한다.
    • 파라미터는 액션 객체를 넣어주면 된다.

[index.js]

import { createStore } from 'redux';

const divToggle = document.querySelector('.toggle');
const counter = document.querySelector('h1');
const btnIncrease = document.querySelector('#increase');
const btnDecrease = document.querySelector('#decrease');

const TOGGLE_SWITCH = 'TOGGLE_SWITCH';
const INCREASE = 'INCREASE';
const DECREASE = 'DECREASE';

const toggleSwitch = () => ({ type : TOGGLE_SWITCH });
const increase = difference => ({ type : INCREASE, difference });
const decrease = () => ({ type : DECREASE });

const initialState = {
    toggle: false,
    counter: 0
}

// state가 undefined일 때는 initialState를 기본값으로 사용
function reducer(state = initialState, action) {
    // action.type에 따라 다른 작업을 처리함
    switch (action.type) {
        case TOGGLE_SWITCH:
            return {
                ...state, //불변성 유지를 해 주어야 한다.
                toggle: !state.toggle
            };
        case INCREASE:
            return {
                ...state,
                counter: state.counter + action.difference
            };
        case DECREASE:
            return {
                ...state,
                counter: state.counter - 1
            };
        default:
            return state
    }
}

const store = createStore(reducer)

const render = () => {
    const state = store.getState(); // 현재 상태를 불러온다.
    // 토글 처리
    if (state.toggle) {
        divToggle.classList.add('active');
    } else {
        divToggle.classList.remove('active')
    }
    // 카운터 처리
    counter.innerText = state.counter;
};

render();

store.subscribe(render)

divToggle.onclick = () => {
    store.dispatch(toggleSwitch());
};
btnIncrease.onclick = () => {
    store.dispatch(increase(1));
};
btnDecrease.onclick = () => {
    store.dispatch(decrease());
};

 

[결과]

 

3. 리덕스의 세 가지 규칙

3.1. 단일 스토어

  • 하나의 애플리케이션 안에는 하나의 스토어가 들어있다.
    • 여러 개 가능은 하지만 상태 관리가 복잡해질 수 있으므로 권장하지 않는다.

 

3.2. 읽기 전용 상태

  • 리덕스 상태는 읽기 전용이다.
  • 기존에 리액트에서 setState를 사용하여 state를 업데이트할 때도 객체나 배열을 업데이트 하는 과정에서 불변성을 지켜 주기 위해 spread 연산자를 사용하거나 immer와 같은 불변성 관리 라이브러리를 사용했다.
    • 리덕스도 마찬가지이다.
    • 상태를 업데이트할 때 기존의 객체는 건드리지 않고 새로운 객체를 생성해줘야 한다.
  • 리덕스에서 불변성을 유지해야 하는 이유
    • 내부적으로 데이터가 변경되는 것을 감지하기 위해 얕은 비교 검사를 하기 때문
    • 객체의 변화를 감지할 때 객체의 깊숙한 안쪽까지 비교하는 것이 아니라 겉핥기 식으로 비교하여 좋은 성능을 유지할 수 있다.

 

 

3.3. 리듀서는 순수한 함수

  • 변화를 일으키는 리듀서 함수는 순수한 함수여야 한다.
    • 리듀서 함수는 이전 상태와 액션 객체를 파라미터로 받는다.
    • 파라미터 외의 값에는 의존하면 안된다.
    • 이전 상태는 절대로 건드리지 않고, 변화를 준 새로운 상태 객체를 만들어서 반환한다.
    • 똑같은 파라미터로 호출된 리듀서 함수는 언제나 똑같은 결과 값을 반환해야 한다.

 

'Front > React' 카테고리의 다른 글

[React] 리덕스 미들웨어를 통한 비동기 작업 관리  (0) 2021.01.18
[React] 리덕스를 사용하여 리액트 애플리케이션 상태 관리하기  (0) 2021.01.16
[React] Context API  (0) 2021.01.14
[React] 외부 API를 연동하여 뉴스 뷰어 만들기  (0) 2021.01.12
[React] 리액트 라우터 부가 기능  (0) 2021.01.09
    'Front/React' 카테고리의 다른 글
    • [React] 리덕스 미들웨어를 통한 비동기 작업 관리
    • [React] 리덕스를 사용하여 리액트 애플리케이션 상태 관리하기
    • [React] Context API
    • [React] 외부 API를 연동하여 뉴스 뷰어 만들기
    happyso
    happyso

    티스토리툴바