본문 바로가기

배워서 따라하는 포플/react-redux를 이용한 앱

Redux앱(1) - 카운트 앱 생성

실무에서 redux를 사용하면 보통 미들웨어와 같이 사용합니다.

이번 앱은 redux만 배우는 것이라 미들웨어 없이 카운터 앱을 만들겠습니다.

 

react 앱 설치

npx create-react-app ./ --template typescript

react-redux-app폴더를 열고 위 명령어대로 react를 설치합니다.

 

redux 라이브러리 설치

npm install redux --save

위 명령어대로 redux를 설치합니다.

 

Counter UI 및 함수 생성

<div className="App">
  Clicked: times
  <button>
    +
  </button>
  <button>
    -
  </button>
</div>

App.tsx의 UI입니다.

 

Reducer 생성

const counter = (state = 0, action: {type: string}) => {
  switch(action.type) {
    case "INCREMENT":
      return state + 1;
    case "DECREMENT":
      return state - 1;
    default:
     return state;
  }
}

export default counter;

src폴더 안에 reducer폴더 안에 index.tsx파일의 코드입니다.

 

Store 생성 및 Action 전달

import {createStore} from 'redux';
import counter from './reducer';
const store = createStore(counter);

index.tsx 파일에 createStore과 방금 만든 counter를 import한 후 store에 저장합니다.

 

getState()

app의 현재 상태 트리를 반환합니다. store의 redux가 반환한 마지막 값과 같습니다.

<App
  value={store.getState()}
  onIncrement={() => store.dispatch({type: "INCREMENT"})}
  onDecrement={() => store.dispatch({type: "DECREMENT"})}
/>

index.tsx파일의 render부분 App추가 코드입니다.

App.tsx에 돌아와서 props를 내려 받고 type도 명시해줍니다.

 

subscribe()

change listener를 추가합ㄴ디ㅏ. 작업이 전달될 때마다 호출되며 상태 트리의 일부가 잠재적으로 변경되었을 수 있습니다.

그런 다음 getState()를 호출하여 콜백 내부의 현재 상태 트리를 읽을 수 있습니다.

App.tsx의 root.render()를 콜백함수로 만들고 subscribe를 통해 실행되면 정상적으로 작동됩니다.