본문 바로가기
Study/Udemy-React-완벽 가이드

18.1 리덕스에 뛰어들기: 기초 (feat. 유데미 React 완벽 가이드)

by NFAP0221S 2022. 6. 12.

https://www.udemy.com/course/best-react/

 

【한글자막】 React 완벽 가이드 with Redux, Next.js, TypeScript

Javascript부터 웹 어플리케이션 배포까지, React와 프론트엔드 최신 기술을 가장 쉽고 확실하게 배우는 법

www.udemy.com

이 게시물은 유데미 React 완벽 가이드 강의를 보고 메모를 남기는 게시물 입니다.


Redux 패키치 설치

redux 패키지와 react-redux 패키지를 설치해야한다.

react-redux는 리액트와 리덕스를 바인딩 해주어 리액트,리덕스  스토어, 리듀서에 간단히 접속하게 한다.

npm install redux react-redux

다음 package.json을 확인하여 확인을 해주면 된다.

리덕스 기초 코드

이전 글과 이 글의 주석을 참고하며 리덕스 기초 알아보기.

const redux = require("redux"); // 서드파티 패키지를 임포트하기 위한 기본 노드 JS 임포트 구문

// 리듀서 함수 생성
const counterReducer = (state = { counter: 0 }, action) => {
  if (action.type === "increment") {
    return {
      counter: state.counter + 1,
    };
  }

  if (action.type === "decrement") {
    return {
      counter: state.counter - 1,
    };
  }

  return state;
};

const store = redux.createStore(counterReducer); // redux 라이브러리에서 온 메서드, 저장소 생성

// console.log(store.getState());

// 구독 함수, 어떠한 파라미터도 받지 않음
// 구독함수의 상태가 변경되면 getState로 변경된 후의 최신 상태를 받는다.
const counterSubscriber = () => {
  // getState는 createStore() 로 생성된 저장소에서 사용할 수 있는 메서드, 최신 상태 제공
  const latestState = store.getState();
  console.log(latestState);
};

// subscribe는 counterSubscriber 함수를 취한다.
// 리덕스는 데이터와 저장소가 변경될 때마다 실행해준다.
store.subscribe(counterSubscriber);

store.dispatch({
  type: "increment",
});

store.dispatch({
  type: "decrement",
});