[react] 리덕스 톺아보기

KoEunseo·2023년 1월 8일
0

리액트

목록 보기
6/21

리덕스... 봐도봐도 써봐도 모르겠다... 허허
최근 유데미에서 강의를 구매했는데, 리덕스 부분을 먼저 보고 이에 대해 정리를 좀 해보려고 한다.

👉 스타트!

리덕스 기본개념

리듀서 함수는 항상 두개의 인자를 받는다.

  • 하나는 기존의 상태(old state),
    하나는 발송된 액션(dispatched action)이다.
  • 리듀서 함수는 새로운 상태 객체를 리턴해야한다.
    리듀서는 그래서 순수함수가 되어야 한다!

Q) 순수함수? A) 같은 input 같은 output, 즉 no Side Effect

store와 리듀서가 함께 작업하기 때문에, store에 리듀서를 알려야 한다.

Basic redux example (in javascript)

const redux = require("redux");
const counterReducer = (state = { counter: 0 }, action) => {
  if (action.type === "increment") {
    return {
      // 어떤 상태든 리턴 가능. 보통은 객체를 리턴한다.
      counter: state.counter + 1
    };
  }
  return state;
};
const store = redux.createStore(counterReducer);
const counterSubscriber = () => {
  //구독. 파라미터를 받지 않는다.
  //저장소에서 getState를 불러와 현재 상태를 받을 수 있다.
  const latestState = store.getState();
  console.log(latestState);
};
//subscribe: 함수를 파라미터로 받는다. store이 변할때마다 실행된다.
store.subscribe(counterSubscriber);
//액션을 발송하는 메소드: dispatch
store.dispatch({ type: "increment" });
profile
주니어 플러터 개발자의 고군분투기

0개의 댓글