키워드: Reconciliation, Virtual DOM, Diffing algorithm, Rendering
참고: https://youtu.be/7YhdqIR2Yzo
[1] React Components / React Elements / Component Instances
Component call → React.createElement function calls(compile elements) → Function returns an object($$typeof, key, props, ref, type(name of element): it describe DOM node(HTML element) & component instance)
[2] Reconciliation(재조정)
1. All React does is create a tree of elements. This is very fast, because React elements are just plain JavaScript objects.
2. This tree of elements is kept in memory, it is the virtual DOM
3. Sync the virtual DOM with the real DOM
4. During initial render, React insert the full tree. This costs expensive.
[3-1] Diffing algorithm assumptions
When tree of elements changes, React compare new tree from old tree.
Normally: n elements => nⁿ operations (ex: 10 elements => 1,000,000 operations)
React: n elements => n operations (ex: 10 elements => 10 operations)
[3-1] Diffing algorithm operation
case#1 If root element is different ↓↓
React will rebuild the tree from scratch. All component instances in the old tree are destroyed along with their current state.
case#2 If element does not change and attribute changes. Only state will change
case#3 Because first and second are same, third element will insert into the element.
case#4 Because all of elements are different, React will destory old tree and create new tree.
case#5 React will notice that which elements are same and verify the change more easily
[4] Render
ReactDOM calls render method and it finally shows on screen.
위와 같이 리액트는 ReactDOM이라는 renderer package를 이용해 최종적으로 DOM tree를 그려준다. 그런데 위와 같이 한번만 호출했을뿐인데 리액트는 데이터의 변화값에 따라 실시간으로 렌더할 수 있을까?(어떻게 최신상태를 유지할까?)
useState를 뜯어보면 리액트는 "__currentDispatcher"르는 dispach 메서드를 호출한다. 이는 ReactDOM과 연결되어있고, 그렇기 때문에 컴포넌트는 state를 최신상태로 유지하며 반응하는 것이다.
'React.js' 카테고리의 다른 글
[심층분석] useState (1) | 2022.10.14 |
---|---|
[심층분석] useEffect & dependency array (feat. API race condition, useEffect 클린업 코드) (0) | 2022.10.12 |
[애니메이션] GSAP 적용 (0) | 2022.08.12 |
깨달음 (리액트 비동기) (0) | 2022.08.11 |
[CSS-in-JS] styled-components (0) | 2022.08.06 |
댓글