본문 바로가기
개발 지식 A+/FE

Redux

by ddubbu 2021. 1. 26.
728x90
반응형

React를 공부하면서, 상태를 관리할 수 있는 기술은 상당히 매력적이었다. 하지만, 최상위에 state를 두었을 경우 매번 Prop drilling, Lifting state up 건너건너 state에 접근하기가 영 불편한게 아니었다. 그리하여, 상태를 한 곳에서 관리해주는 Redux 라이브러리를 함께 공부해보자.

 

생활코딩 영상 참고 ㄱㄱ

이번엔 왜 공식 문서 따라하기가 어렵지 - codesandbox 다시 gitit!!


What is Redux?

 

preidictable state container for JavaScript apps.

 

React 와 같은 다른 view library에서도 사용 가능.

 

 

Installation

 

solo package

// only Redux toolkit
$npm install @reduxjs/toolkit


// or Redux Core
$ npm install redux

 

Create a React Redux App

npx create-react-app project_name --template redux

 

 

 

Redux의 기본 개념 : 3가지 원칙

 

여기 이미지 예쁜 듯 

medium.com/@ca3rot/%EC%95%84%EB%A7%88-%EC%9D%B4%EA%B2%8C-%EC%A0%9C%EC%9D%BC-%EC%9D%B4%ED%95%B4%ED%95%98%EA%B8%B0-%EC%89%AC%EC%9A%B8%EA%B1%B8%EC%9A%94-react-redux-%ED%94%8C%EB%A1%9C%EC%9A%B0%EC%9D%98-%EC%9D%B4%ED%95%B4-1585e911a0a6

 

Redux Architecture

 

https://medium.com/@ankitgoyal_41900/should-we-take-the-redux-path-3bc47ca6e281

  1. Single source of truth : Store
    상태가 관리되는 오직 하나의 공간
  2. State is read-only (= not changed directly)
    but we have change info  : Action 
    어떠한 액션을 취할지 정의해 놓은 객체
    ;; 여기 애매함

    with Redux hooks(useSelector, useDispatch)
    Component <-- useSelector -- State
    Action -- useDispatch --> Reducer
  3. Changes are made with pure functions : Reducer
    현재 상태와 Action을 이용해 새로운 상태를 만들어냄.
    Dispatch는 Action을 전달한다고? 그럼 위 그림 이상한데?
    더 자세하게 말하면, Action 객체는 Dispatch에게 전달되고, Dispatch는 Reducer 호출해서 새로운 state 생성

    연예사 dispatch 빠르게 보내다 어감

 

 

 

Redux 장점

 

소제목

 

  1. 상태를 예측 가능하게 만들어준다.
  2. 유지보수
  3. (action과 state log 기록 시)디버깅에 유리하다 - Redux Dev Tool
  4. 테스트를 붙이기 쉽다.

 

 

Reducer 주의할 점 : Immutability

 

소제목

 

(변경된 state를 log로 남기기 위해서) Reducer 함수 작성 시 state 업데이트는 immutable한 방식으로 변경해야한다. 

Object.assign 을 통해 새로운 정보를 병합해 리턴한다.

 

daveceddia.com/react-redux-immutability-guide/

 

 

 

기타

 

connect prameter : mapStateToProps, mapDispatchToProps &

Redux hooks (최근, 보다 쉬움) : useSelector(), useDispatch

 

(변경된 state를 log로 남기기 위해서) Reducer 함수 작성 시 state 업데이트는 immutable한 방식으로 변경해야한다. 

Object.assign, 배열은 ? 무슨 copy ? 을 통해 새로운 정보를 병합해 리턴한다.

 

Presentational Component 어떻게 보여지는 가?

Conatiner Component 어떻게 동작하는가? ( state 값을 가져와 출력함.)

 

Pure Redux Library Review!

 

 


 

참고자료

www.robinwieruch.de/react-redux-tutorial

facebook.github.io/flux/docs/in-depth-overview/

네이버

d2.naver.com/helloworld/1848131

 

 

반응형

'개발 지식 A+ > FE' 카테고리의 다른 글

Nuxt.js 시작하기  (0) 2021.02.21
Vue.js 시작하기  (0) 2021.02.20
Hooks 공식문서로 이해하기  (0) 2021.01.26
this 키워드  (0) 2021.01.26
how to show cookie headers at client  (0) 2021.01.20