[React-Redux] [1] 시작하기

김영인·2021년 11월 3일
0
post-thumbnail

유데미 강의를 통해 정리한 내용입니다

1. Context API의 단점

강의에서 말하길...
Redux is an alternative to the Context API

둘 다 Cross-Component/App-Wide state를 관리하기 좋지만 왜 저렇게 언급했는지,
Context의 단점을 살펴보면서 알아보자!

  • context API의 단점
    1) Setup 과정이 복잡하며, 큰 앱을 만들 떄 이 단점이 더 부각된다.
    각각의 context를 만들 때

    하나의 context에 담을 때
    둘 다 영...
    2) 퍼포먼스가 별로 : 높은 빈도로 변경되는 state에게는 적합하지 않음

    "Redux는 이 두 단점을 해결한다!!"

2. Redux의 핵심 콘셉트

  • 모든 state는 한 곳(Central Data(Store))에 저장한다.
  • components는 store의 특정 state를 구독(subscription)한다.
  • components는 절대 직접적으로 store data(state)를 조작하지 않는다.
  • Reducer Function만이 store data(state)를 변경(mutate, change)할 수 있다.
  • component가 action을 보내서(dispatch) Reducer 함수를 실행시킨다.

3. Reducer의 구조

  • input(매개변수): 'Old(previous, current) state', dispatched 'action'
  • output(return 값): New State(value나 object)

4. redux 기본(in vanilla JS) : store, reducer, state, subscribe, dispatch

// redux 설치하기
npm i redux
// redux 가져오기
const redux = require("redux"); // nodejs 예시

//reducer : state 변경 함수. 첫 실행 시 필요한 default value 필요
// 위 reducer 설명 참고
const exampleReducer = (state = { counter: 0 },action) => {
  if (action.type === "increment") {
    return {
      counter: state.counter + 1
    };    
  } else if (action.type === "decrement") {
    return {
      counter: state.counter - 1
    };    
  } else {
    return state
  };
};

//store : redux.createStore(reducer)로 생성. reducer는 store data를 변경할 reducer 넣기
const store = redux.createStore(exampleReducer);

// state : store.getState()
const latestState = store.getState();

// subscribe : store.subscribe(해당 store data(state) 변경 시 실행할 함수)
const exampleSubscriber = () => {
	const latestState = store.getState();
  	console.log(latestState);
};
store.subscribe(exampleSubscriber);

// dipatching action: 인자로 type 키를 가진 객체 필요
store.dispatch({type: "increment"})
profile
꾸준히, 그리고 정직하게 성장하는 프론트엔드 개발자

0개의 댓글