Redux 기초 - 바닐라 자바스크립트에서 리덕스 사용해보기
포스트
취소

Redux 기초 - 바닐라 자바스크립트에서 리덕스 사용해보기

노마드코더 - 초보자를 위한 리덕스 101을 듣고 정리한 내용입니다.

Redux

  • 자바스크립트 앱을 위한 예측 가능한 상태 컨테이너(공식페이지에 나온 문구)
  • React에서만 사용할 수 있는게 아니라, 자바스크립트의 상태 관리를 위한 라이브러리이다.
    • 상태(state) : 내 application에서 변경되는 데이터
  • 설치 : npm install redux

Redux 적용하기 전 코드

  • add, minus 버튼을 가지는 counter

    counter

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
// index.js
const add = document.getElementById("add");
const minus = document.getElementById("minus");
const number = document.querySelector("span");

// 초기값 설정
let count = 0;

// 화면에 표시
number.innerText = count;

// count가 변할 때 마다 실행할 함수
const updateText = () => {
  number.innerText = count;
};

// Add 버튼 클릭 시 count 1 증가
const handleAdd = () => {
  count = count + 1;
  updateText();
};

// Minus 버튼 클릭 시 count 1 감소
const handleMinus = () => {
  count = count - 1;
  updateText();
};

// 각 버튼에 이벤트 할당
add.addEventListener("click", handleAdd);
minus.addEventListener("click", handleMinus);

// index.html
<body>
  <button id="add">Add</button>
  <span>0</span>
  <button id="minus">Minus</button>
</body>;

Redux 적용 후 코드 및 설명

store

  • 상태 정보를 담는 곳
  • createStore 함수를 사용해서 생성한다.
  • 인자로 reducer함수를 받는다.
  • store을 만들면 인자로 받는 함수를 기본 state로 불러온다.
1
2
3
import { createStore } from "redux";

const countStore = createStore(countModifier);

reducer 함수

  • state를 변경하는 함수로, return하는 데이터가 state의 값이 된다.
    • counter에서는 count가 state에 해당한다.
  • 인자를 2개 받는다.
    • state : state로 지정한 변수
    • action : action은 ‘type’속성을 가진 object로, action의 type에 따라 로직을 작성한다.
  • reducer는 4개의 함수를 갖는다. dispatch(), subscribe(), getState(), replaceReducer()
  • reducer.getState() : return된 값을 가져온다 → 현재 state값
1
2
3
4
5
6
7
8
9
10
11
12
// state 초기값을 0으로 설정(count = 0)
const countModifier = (count = 0, action) => {
  // if - else if - else문을 써도 되지만 가독성을 위해 switch를 사용했다.
  switch (action.type) {
    case ADD:
      return count + 1;
    case MINUS:
      return count - 1;
    default:
      return count;
  }
};

dispatch

  • reducer함수의 action 파라미터에 메세지를 보낸다.
  • 보낸 메세지의 내용에 따라 reducer 함수에서 로직을 작성한다.
  • object로 작성해야 하며 반드시 type이 있어야 한다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
const add = document.getElementById("add");
const minus = document.getElementById("minus");

const handleAdd = () => {
  // dispatch를 호출하면 countModifier(count = 0, {type: "ADD"}) 이렇게 호출된다.
  countStore.dispatch({ type: ADD });
};

const handleMinus = () => {
  countStore.dispatch({ type: MINUS });
};

add.addEventListener("click", handleAdd);
minus.addEventListener("click", handleMinus);

subscribe

  • store 안에 있는 변화를 알 수 있게 해준다.
1
2
3
4
5
6
const onChange = () => {
  number.innerText = countStore.getState();
};

// state가 변경되면 onChange함수 실행
countStore.subscribe(onChange);

전체 코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import { createStore } from "redux";

const add = document.getElementById("add");
const minus = document.getElementById("minus");
const number = document.querySelector("span");

number.innerText = 0;

const ADD = "ADD";
const MINUS = "MINUS";

const countModifier = (count = 0, action) => {
  switch (action.type) {
    case ADD:
      return count + 1;
    case MINUS:
      return count - 1;
    default:
      return count;
  }
};

const countStore = createStore(countModifier);

const onChange = () => {
  number.innerText = countStore.getState();
};

countStore.subscribe(onChange);

const handleAdd = () => {
  countStore.dispatch({ type: ADD });
};

const handleMinus = () => {
  countStore.dispatch({ type: MINUS });
};
add.addEventListener("click", handleAdd);
minus.addEventListener("click", handleMinus);

출처) 노마드코더 - 초보자를 위한 리덕스 101


이 기사는 저작권자의 CC BY 4.0 라이센스를 따릅니다.