Level 2: react-shopping-cart 학습로그

동동·2021년 6월 23일
1

0. PR 링크

1. Redux는 무엇인가

JS App을 위한 예측가능한 상태관리 라이브러리입니다. Redux는 framework agnostic 하여, framework에 종속되지 않고, 다양한 framework와 같이 사용가능합니다. Reduxd의 major 버젼이 나온 것은 6년 전으로서, 생태계가 매우 방대하고, 공식문서들이 매우 잘 갖추어져 있으며, 관련된 자료들을 웹상에서 매우 쉽고 많이 찾을 수 있습니다다. 다만, 요즘에는 다양한 상태관리 라이브러리들(MobX, React Query, Recoil 등)이 발표되어 차츰 인기가 시들해지고 있습니다.

Redux의 특징은 다음과 같습니다.

  • state는 단일 store에서 관리된다.
  • state를 갱신하기 위한 유일한 방법은 action을 store에 dispatch하는 것이다.
  • action 은 무엇을 수행할지를 나타내는 Plain Old Javascript Object이다.
  • action에 따라 state를 어떻게 갱신할지를 명시하기 위해, reducer 를 작성하여야 한다.
  • reducer는 기존 state와 action을 바탕으로 새로운 state를 반환하는 순수함수이다.
  • store의 state가 갱신되면 store를 subscribe하는(store에 이미 등록해둔) 콜백함수가 실행된다. UI를 업데이트하는 함수를 등록해두면, state 변화에 따라 UI가 자동으로 변경되게끔 할 수 있다.

React 에서의 쓰임새

React에서 Component는 tree 구조를 이루고 있는데, 이는 parent - child 상하구조로 이루어져있다는 뜻입니다. 따라서 어떠한 state가 매우 많은 component에서 사용되는 경우에, 공통되는 최상위 부모에서 state를 정의하고 이를 사용하는 자식에게까지 props로 전달하는 경우가 많은데, 부모부터 자식까지의 hierarchy 가 굉장히 깊고 멀다면, 이러한 props drilling 이 매우 번거로운 작업이 될 수 있습니다. 또한 state는 사용되는 곳과 정의되는 곳이 가까워야 유지보수하기 쉬울터인데, 상위의 부모에서 정의하고 사용은 최하위의 자식에게서 사용하는 패턴은 유지보수를 어렵게 하는 요인입니다.

다양한 컴포넌트에서 사용되는 상태를 Redux 에서 전역으로 관리하여, 어디서든 접근가능하게 하면 depth가 깊어지는 문제를 해결할 수 있다. 다만, 이는 반대로 어느 컴포넌트에서는 Redux를 통하여 state에 접근이 가능하게 되므로, state가 더럽혀지지 않도록 하는 것이 중요하다.

https://redux.js.org/

2. Redux Toolkit

  • RTK란?

  • RTK의 장단점은?

    • Ducks Pattern. 하나의 파일 내에 action creator, reducer를 모두 정의한다. 이를 편하게 해주는 createSlice 함수를 내장하고 있다.
    • 디버깅을 편리하게 해주는 Redux dev tools, 비동기 처리를 지원하는 thunk, reducer 내에서 state를 mutable 하게 사용할 수 있도록 해주는 immer 등 다양한 미들웨어가 이미 포함되어 있으며, 이를 (out of box!) 아무 설정 없이 바로 사용할 수 있어, DX를 크게 증진시킬 수 있다.
    • 단점은, 개인적으로 없다고 생각한다. 사용법 숙지에 일부 시간이 드는 점. 꽤나 opinionated 하다는 점으로 인해 호불호가 갈릴 수 있으나, Redux maintainer가 만든 Redux 사용시의 best practice를 모았다는 점에서, 사용하지 않을 이유가 없다.

https://redux.js.org/introduction/getting-started#installation

3. react-redux: UI tool + redux 동작 원리

각 Component에서 useSelector를 하는 건, 각 Component가 store를 subscribe 하는 것이다.

Redux 자체는 subscribe 한 콜백함수를 다 실행시키며, 별도의 최적화를 하지 않는다. 다만, react-redux와 같이 redux를 wrapping 하는 UI tool 의 경우, select 해오는 state가 변화하지 않았으면 re-rendering 되지 않게 하는 자체적인 최적화가 수행되어 있다.

Redux itself is a standalone library that can be used with any UI layer or framework, including React, Angular, Vue, Ember, and vanilla JS. Although Redux and React are commonly used together, they are independent of each other.

If you are using Redux with any kind of UI framework, you will normally use a "UI binding" library to tie Redux together with your UI framework, rather than directly interacting with the store from your UI code.

React Redux is the official Redux UI binding library for React. If you are using Redux and React together, you should also use React Redux to bind these two libraries.

To understand why you should use React Redux, it may help to understand what a "UI binding library" does.

React-Redux is conceptually pretty simple. It subscribes to the Redux store, checks to see if the data your component wants has changed, and re-renders your component.

The Standard UI Update Cycle

Every Redux UI integration layer is simply a fancier version of those steps.

Using Redux with any UI layer requires the same consistent set of steps:

  1. Create a Redux store
  2. Subscribe to updates
  3. Inside the subscription callback:
    1. Get the current store state
    2. Extract the data needed by this piece of UI
    3. Update the UI with the data
  4. If necessary, render the UI with initial state
  5. Respond to UI inputs by dispatching Redux actions

Every Wrapper Component Instance is a Separate Store Subscriber

This one's pretty simple. If I have a connected list component, and it renders 10 connected list item children, that's 11 separate calls to store.subscribe(). That also means that if I have N connected components in the tree, then N subscriber callbacks are run for every dispatched action!.

Every single subscriber callback is then responsible for doing its own checks to see if that particular component actually needs to update or not, based on the store state and props.

https://blog.isquaredsoftware.com/2018/11/react-redux-history-implementation/

4. <img>는 self-closing tag인가요?

html elements는 여섯가지로 분류할 수 있습니다.

  1. Void elements
    area, base, br, col, embed, hr, img, input, link, meta, param, source, track, wbr
  2. The template element
    template
  3. Raw text elements
    script, style
  4. Escapable raw text elements
    textarea, title
  5. Foreign elements
    Elements from the MathML namespace and the SVG namespace.
  6. Normal elements
    All other allowed HTML elements are normal elements.

<img>는 void elements입니다. void elements는 오직 start tag만 가지고 있으며 end tag는 반드시 없어야 합니다. end tag가 없으므로, start tag 와 end tag로 감싸는 contents를 포함할 수 없습니다. (없어야 합니다.)

역사적으로 보면 HTML4에서는 이 슬래쉬(/)가 있으면 해당 void elements는 invalid 한 것으로 간주되었습니다. 하지만 현재 W3C의 HTML validator는 슬래쉬(/)가 있는 void elements도 valid 한 것으로 보고 있습니다.(비록 경고를 내긴 하지만...)
HTML4와는 반대로 XHTML에서는 반드시 슬래쉬(/)가 있어야 합니다.

현재 Living Standard인 HTML5의 start tags의 형식에 따르면, void elements의 경우 start tag 의 닫는 꺽쇠(>) 전 슬래쉬(/)는 optional입니다. 이 슬래쉬(/)는 아무 영향을 미치지 않습니다. (아마 HTML4, XHTML 과의 하위 호환성을 위한 것으로 생각됩니다)

따라서, best practice는 슬래쉬(/)를 항상 기재하여 end tag가 없다는 것을 명확하게 보여주는 것입니다. HTML4, HTML5 모두 valid 한것으로 간주되며, XHTML과의 정합성도 꾀할 수 있습니다.

https://html.spec.whatwg.org/multipage/syntax.html#void-elements

https://html.spec.whatwg.org/multipage/syntax.html#start-tags

http://validator.w3.org/

profile
작은 실패, 빠른 피드백, 다시 시도

0개의 댓글