||리덕스 초심자 #1|| Redux의 기본 개념과 원리

윤코코·2021년 10월 21일
0

Redux

목록 보기
1/3
post-thumbnail

🚩 Redux 기초 정리하기

이제야 React Redux가 무슨 역할을 하는건지 제대로 알았다.
그리고 이제야 공식문서의 첫 페이지를 이해할 수 있게 되었고,
이제야 공식문서를 통해서 어떻게 공부하면 되는지도 감이 잡혔다.
역시 기초부터 다지는 게 답이다.

React Redux를 하기 전에 Pure Redux부터 정리하고 넘어가자.

Redux

Redux is a predictable state container for JavaScript apps.

Redux is most useful when in cases when:

  • You have large amounts of application state that are needed in many places in the app
  • The app state is updated frequently
  • The logic to update that state may be complex
  • The app has a medium or large-sized codebase, and might be worked on by many people
  • You need to see how that state is being updated over time

(*출처: When should I use Redux?)

핵심 원리

핵심 원리는 공식문서 Core Concepts | Redux에서 아주 친철하게 설명해주고 있다.
처음에는 정말 느릿느릿하게 설명해주는 생활코딩의 강의를 두번씩 돌려보고
정말 쉽게 설명해주는 노마드코더 강의도 두번을 봤어도 뭔 뜬구름 잡는 소린가 했는데,
이제는 직접 써보고 필요성을 느낀 뒤여서 그런지 더 잘 이해가 되고 있다.
(아래 코드 예제는 모두 공식문서에서 가져왔다.)

  • state를 변경하기 위해서는 반드시 actiondispatch 해야 한다.
    - action은 state를 어떻게 바꿀지에 대한 키워드(type)와 변경에 필요한 값(payload)을 들고 있다.
    - 임의로 state가 바뀌어 버그가 생기는 것을 막을 수 있다.
{ type: 'ADD_TODO', text: 'Go to swimming pool' }
{ type: 'TOGGLE_TODO', index: 1 }
{ type: 'SET_VISIBILITY_FILTER', filter: 'SHOW_ALL' }
  • state와 action을 묶어서 들고 있는 것이 reducer이다.
    - reducer는 state를 바꾸는 상세한 방법을 가지고 있다.
    - 따라서 state와 action을 받아 변경된 state를 반환한다.
    - 이렇게 state별로 reducer(작은 함수)를 만들어 관리하기 때문에 큰 앱에서 상태관리를 하기 용이하다.
function todos(state = [], action) {
  switch (action.type) {
    case 'ADD_TODO':
      return state.concat([{ text: action.text, completed: false }])
    case 'TOGGLE_TODO':
      return state.map((todo, index) =>
        action.index === index
          ? { text: todo.text, completed: !todo.completed }
          : todo
      )
    default:
      return state
  }
}
  • 그리고 이 모든 reducer를 모아 하나의 root reducer로 만들어 store에 연결해준다.
    - store는 앱 전체의 state를 보관하고 관리하는 곳이다.
    - store는 reducer 하나만 받는다.
    - redux는 이를 위해 combineReducers라는 함수를 제공한다.
function todoApp(state = {}, action) {
  return {
    todos: todos(state.todos, action),
    visibilityFilter: visibilityFilter(state.visibilityFilter, action)
  }
}

전체 폴더 구조

  • components
    • common
    • todos
      - index.js
  • features
    • todos
      - todosSlice.js
    • filters
      - filtersSlice.js
  • App.js
  • index.css
  • index.js
  • reducer.js
  • store.js

더 알아야 할 것들

  • getState
  • subscribe
  • middleware
  • actionCreator

참고자료

노마드코더 [초보자를 위한 리덕스 101]
리덕스 공식문서 https://redux.js.org/

profile
Web Front-End Developer

0개의 댓글