[Redux] Store, Reducer, Dispatch, Action, Subscriptions

정세영·2022년 11월 7일
0

Redux

목록 보기
1/2
post-thumbnail

Redux를 사용하는 이유


Store

변경되는 data(state)를 넣는 곳

redux 에는 createStore라는 함수가 내장 되어 있다.
store가 하는 일은 기본적으로 data를 넣을 수 있는 장소를 생성하는 것이다.
store가 만들어지면 reducer라는 함수를 필요로 한다. (없으면 에러남)


Reducer

reducer는 data를 변경하는 함수다.

하지만 변경하는 로직 없이 return해도 그 값이 바로 data가 될 수도 있다.

//reducer
const countModifier = () => {
  return "hello";
};

//store
const countStore = createStore(countModifier);

console.log(countStore.getState());//hello

Reducer로 data 변경하는 방법

initializing State

store를 생성하면 initial state를 갖고 있는 reducer를 불러온다.
initial state는 따로 지정한게 없다면 undefined이다.
인자로 받는 state에 default값을 지정해주면 modify 내용이 없을 때 state 값은 지정해준 default 값이 된다. 이것을 바로 state initializing이라고 한다.

const countModifier = (state = 0) => {
  console.log(state)//0
  return state;
};
const countStore = createStore(countModifier);
console.log(countStore.getState());//0

이제 state(data)를 변경하기 위해서는 actions를 활용해야한다.

Action

action은 redux에서 reducer의 두번째 parameter, 혹은 argument이다. data를 변경할 때 쓰인다.

countModifier함수에서 count를 +1 또는 -1 하고 싶을 때
우리는 countModifier함수에게 우리가 하고 싶은 '행위'를 알려줘야하는데
action은 우리가 전하고자 하는 메세지를 countModifier에게 전달해준다.

그렇다면 어떻게 countModifier에 action을 적용할 수 있을까?
store의 dispatch를 사용하면 된다.

const countModifier = (state = 0, action) => {
  console.log(action);
  //1.{type:"@@redux/INITw.s.x.q.s.7"} => initialized된 function
  //2.{type:{"HELLO"} => 우리가 지정한 type이라는 action
  return state;
};
const countStore = createStore(countModifier);

countStore.dispatch({type:"HELLO"})

dispatch 괄호 안에 쓴게 바로 action 객체이다. (반드시 객체여야함)
countModifier는 2번 불렸다.
처음으로, initialized된 function으로 (신경 안써도 되는 action)
두번째로, 우리가 지정한 type이라는 action으로 불렸다.

정리하자면,
리덕스가 countModifier를 아래와 같이 부를것이다.

countModifier(currentState=0, {type:"HELLO"})

current state는 0 이고 action의 type은 "HELLO"
이게 reducer에 action을 보내서 메세지를 전달하는 방법이다.

count + 1

dispatch로 전달 받은 action으로 우리는 드디어 count + 1를 할 수 있다.

const countModifier = (count = 0, action) => {
  if (action.type === "ADD") {
    return count + 1;
  }
};

const countStore = createStore(countModifier);

countStore.dispatch({ type: "ADD" });

console.log(countStore.getState()); //1

action의 타입이 "ADD"일 때 count + 1을 return하도록 조건문을 작성하는 것이다.
state가 1로 변경된 것을 확인할 수 있다.


Subscriptions

countStore를 콘솔로 찍어보면 dispatch, getState이 보이고 subscribe도 확인할 수 있다.
subscribe가 구독이라는 의미에서 유추할 수 있듯이 subscribe는 store 안에서 일어나고 있는 변화들을 알 수 있게 해준다.

import { createStore } from "redux";

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

number.innerText = 0;

const countModifier = (count = 0, action) => {
  console.log(count, action);
  if (action.type === "ADD") {
    return count + 1;
  } else if (action.type === "MINUS") {
    return count - 1;
  } else {
    return count;
  }
};

const countStore = createStore(countModifier);

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

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

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

Store, Reducer, Dispatch, Action 정리

data의 store를 만들고 (createStore)
reducer함수로 data modifier를 만들고
dispatch를 사용해 메세지를 store에 전송한다.
전송한 메세지는 action에 들어가고
action에 따라 조건문을 만들어서 데이터를 변경하면된다.

profile
룰루랄라 개발일지🎶❤️‍🔥🧑‍💻❤️‍🔥🎵

0개의 댓글