리덕스 공부 #3

min Mt·2020년 5월 8일
0
post-thumbnail

리덕스 공식 튜토리얼 정리

Introduction

리덕스 없이 순수 리액트로 프로젝트를 해보니, 스테이트 관리가 정말 힘들었다. 자식 컴포넌트에서 Inverse Data flow로 state를 바꾸는 것도 나중에 가니 헷갈리고, 자식 컴포넌트들에게 필요한 값들만 props로 전달하는 것도 귀찮고 헷갈리고 그랬다. 그래서 Redux를 한번 써보기 위해 기초부터 꼼꼼하게 공부하면서 정리하는 기록.

Store

  • 스토어는 앱의 state를 가지고 있는 오브젝트 이다.
  • getState()를 통해 state에 접근이 가능하다. 불러오기
  • dispatch(action)을 통해 state의 업데이트가 가능하다.
  • subscribe(listener)를 통해 state의 변화를 감지하고 적절하게 핸들링할 수 있다.
  • store는 앱에 하나만 가지고 있으며, state를 역할별로 나누고 싶은 경우, 앞에서 배운 reducer composition 을 사용하면 된다.

createStore()

스토어를 만들어 보자.

import { createStore } from 'redux' //임포트
import todoApp from './reducers' //우리가 만든 리듀서 / combineReducers
const store = createStore(todoApp)  //스토어 생성

스토어의 argument로는 리듀서를 넣어주고, 2번째 인자로는 initialState를 넣어줄 수 있다.

Dispatching Actions

만든 스토어에 저장되어 있는 state를 변경해 보자

import {
  addTodo,
  toggleTodo,
  setVisibilityFilter,
  VisibilityFilters
} from './actions'

// Log the initial state
console.log(store.getState())

// Every time the state changes, log it
// Note that subscribe() returns a function for unregistering the listener
const unsubscribe = store.subscribe(() => console.log(store.getState()))

// Dispatch some actions
store.dispatch(addTodo('Learn about actions'))
store.dispatch(addTodo('Learn about reducers'))
store.dispatch(addTodo('Learn about store'))
store.dispatch(toggleTodo(0))
store.dispatch(toggleTodo(1))
store.dispatch(setVisibilityFilter(VisibilityFilters.SHOW_COMPLETED))

// Stop listening to state updates
unsubscribe()

예제 코드를 살펴보면 먼저 store.getState()를 통해 state에 접근할 수 있는 것을 알 수 있다.

const unsubscribe = store.subscribe(() => console.log(store.getState()))

이 코드를 통해 store를 구독했다. 구독을 하게 되면, store가 dispatch되어 새로운 state를 반환하고 나면 subscribe의 인자로 넘겼던 함수가 호출된다.
또, subscribe 는 구독을 취소하는 함수를 반환하기 때문에, unsubscribe에 할당해 놓아 필요할 때 구독을 취소한다.

subscribe에 리스너를 등록할 때 주의할 점은, 리스너 안에 다시 dispatch 를 하는 경우이다. 조건을 명확하게 하지 않을 경우 당연하게도 무한루프가 발생한다.

Data flow

이렇게 리덕스를 사용하기 위한 것들 Action, Reducer, Store 를 배웠다.
이것들을 사용하여 데이터 사이클이 어떻게 돌아가는지 살펴보자.
리덕스 데이터 라이프 사이클은 4가지 스텝을 따른다.

  1. store.dispatch(action) 호출
    앱에서 state의 변화가 필요할 때 action 을 dispatch 한다.

  2. store에서 prevState와 action 을 리듀서의 인자로 전달하여 함수 호출
    리듀서는 순수한 함수이기 때문에 전달받은 state와 action에 따라 새로운 state를 반환한다.

  3. Root 리듀서에서 전달받은 스테이트를 single state tree와 합친다.
    리듀서에서 잘게 쪼개진 스테이트를 전달받아서 관련된 스테이트만 리턴하기 때문에,
    이 잘게 쪼개진 스테이트를 root reducer에서 합친다. 이때 사용되는 것이 combineReducers().

  4. 리덕스 스토어에서 합쳐진 state tree를 저장한다.
    이 마지막 과정이 끝난 후 UI 업데이트 등을 한다. 즉, 구독했던 listener들이 호출되면서 UI 업데이트 작업등이 이루어진다.

Next

이렇게 리덕스에 대해 Basic Tutorial에 대해 알아보았다.
원래는 Usage with React가 과정에 있는데 일단은 건너 뛰고
Advanced Tutorial에 대해 공부할 예정이다.
비동기적 액션과 데이터 플로우 등을 학습할 수 있다.

profile
안녕하세요!

0개의 댓글