본문 바로가기
React.js

리액트의 작동원리

by 찬찬2 2022. 10. 6.

키워드: 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) 

 

(barbel) App 컴포넌트는 실제로 오른쪽과 같이 React.createElement 함수를 호출한다.
React.createElement함수는 위와 같은 객체(React elements)를 반환한다.
리액트 컴포넌트가 호출되었을때 반환하는 객체모습(React elements)

[2] Reconciliation(재조정)

1. All React does is create a tree of elements. This is very fast, because React elements are just plain JavaScript objects.

 

React's tree of elements

 

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.

 

React create two different trees. The new tree and old tree, Then React compare these two tree.

 

[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를 최신상태로 유지하며 반응하는 것이다.

 

댓글