ReduxStudy(Store and Reducer)

이승훈·2022년 10월 25일
0

TIL

목록 보기
12/31
post-thumbnail

Store and Reducer

(index.html)
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <meta
      name="description"
      content="Web site created using create-react-app"
    />
    <title>Vanila Redux</title>
  </head>
  <body>
    <button id="add">Plus</button>
    <span></span>
    <button id="minus">Minus</button>
  </body>
</html>
(index.js)
const add = document.getElementById('add');
const minus = document.getElementById('minus');
const number = document.querySelector('span');

let count = 0;

number.innerText = count;

const updateText = () => {
  number.innerText = count;
}

const handleAdd = () => {
  count = count + 1;
  updateText();
};

const handleMinus = () => {
  count = count - 1;
  updateText();
};

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

위의 바닐라 JS 코드를 Redux를 이용해서 바꿔볼것이다.

Redux를 사용하기 위해선 npm i redux를 통해 설치해줘야한다.

이후 index.js에 createStore 라는걸 redux로부터 import 해줘야한다.

import { createStore } from "redux";

이 store라는게 무엇일까?

store는 나의 data를 넣는곳이다.

나의 data는 나의 state를 말한다.

state는 무엇일까?

state는 나의 application에서 바뀌는 data를 말한다.

위의 바닐라 JS에서 바뀌는 data는 count이다.

기타 모든 코드들은 count를 수정하기 위해 존재한다.

그리고 우리가 html에게 count를 업데이트 하라고 알려줘야한다.

자 Redux에는 createStore라는 function 이 있다.

store가 하는 일은 기본적으로 나의 data(State)를 넣을 수 있는 장소를 생성한다.

그게 바로 Redux가 가장 잘 하는것이기 때문이다.

Redux는 나의 date(state)를 관리하는것을 도와주기 위해 만들어졌다.

그라고 그 data는 store라는 곳에 저장되어야 한다.

store는 아래와같은 방법으로 만들 수 있다.

const reducer = () => {};

const store = createStore(reducer);

위와같이 작성함으로서 store와 빈 reducer가 생긴것이다.

정리해보자면

store를 만들었고 store는 나의 data를 저장하는 곳이다.

store를 만들게되면 reducer를 만들어야한다.

reducer는 나의 data를 modify 하는 함수다.

위의 바닐라JS 예시에 빗대어보자면 count를 increase하거나 decrease하는것이다.

그리고 이 reducer가 return하는 값이 나의 application에 있는 data가 된다.

  1. reducer는 나의 data를 바꿔준다.
  2. reducer가 return하는것은, 나의 application의 data가 된다.

이제 실제 코드로 작성해보자.

나의 reducer(countModifier)는 state를 return 해줄것이다.

내가 application의 data를 modify 하고 싶으면 countModifier를 사용하면 된다.

countModifier는 state를 argument(인자)로 가지게 될 것이고

인자로 받은 state를 잘 수정하여 return해주면 되는것이다.

오직 countModifier(reducer)만이 data(state)를 modify할 수 있다.

즉, 유일하게 한 개의 함수만이 data를 modify할 수 있는것이고 이것이 redux의 강력한 기능인것이다.

redux는 data가 기본적으로 한 곳에만 있고 그곳이 바로 reducer 함수이다!

import { createStore } from "redux";

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

const countModifier = state => {
  console.log(state);
  return state;
};

const countStore = createStore(countModifier);

위의 코드에서 무슨일이 일어나고 있냐면,

우리가 store를 만들면, countModifier의 initial state를 불러온다.

하지만 위의 코드에서 countModifier의 state의 초기값은 그냥 undefined다.

그러니 아래처럼 state의 default값을 정해주면 된다.

import { createStore } from "redux";

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

const countModifier = (state = 0) => {
  return state;
};

const countStore = createStore(countModifier);
console.log(countStore.getState())

위의 코드처럼 getState메소드를 통해 store의 state값을 가져올 수 있고 콘솔창을 통해 확인해본결과

초기값으로 0이 잘 출력되는것을 볼 수 있었다.

기억하자 오직 countModifer(reducer)만이 state를 modify할 수 있다.

그럼 어떻게 저 state를 변경할 수 있을까?

그것은 action을 통해서 가능하다.

그 action에 대한것은 다음 글에..

profile
Beyond the wall

0개의 댓글