React Virtual Dom under the hood
Asked Answered
B

2

6

I've read from the sources that If I update the state of any component than the whole virtual dom will be render ? Is It True ? If Yes, Then Why render method of all component not called ?

Also, Need some clarification on below point -

  • What is Virtual Dom actually ? Any practical example for that ?
  • I assuming that If we compare the virtual dom with actual dom, Virtual dom takes little time to update the dom than real dom. But how can practically prove that ?

  • How react uses diffing algorithm to update only respective component In which changes happen (If I used setState method)

Any video lecture for that would be really appreciated.

Birth answered 22/9, 2017 at 4:24 Comment(1)
I've read from the sources… — Where did you read that? What sources? Why don't you include in your question?Licence
P
2

No, what you've read is incorrect.

When you update the state of a component, meaning you have changed part of the virtual DOM, You'd be changing ONLY that specific part of React's virtual DOM and nothing else.

All other components do not get re-rendered whatsoever.

An answer to your questions:

  1. Virtual DOM is a representation of the actual DOM in plain JavaScript object. Comprehensive details on what is virtual DOM can be found in this stackoverflow question and this medium article

  2. Manipulating the real DOM is indeed very expensive in regards to efficiency. On the other side, virtual DOM is very efficient. Here are a couple of articles which can help you understand how: Codecademy and Medium article

  3. Codecademy explains how diffing algorithm works but you can also read the following for further information about mentioned algorithm on React's official documentation.

I believe the articles I found and listed here are sufficient to understand the virtual DOM, the performance difference between virtual DOM and real DOM and how does the diffing algorithm works

Perish answered 22/9, 2017 at 5:56 Comment(0)
A
0

If the state or the props of a certain component changes, so this component and it's child component will be rerender, another words - the render method of all these components will be called. If you wonder why the render method of your component has not been called, please insert your snippet of code.

Answers to your sub-questions:

  1. Virtual dom is just representation of real dom. Virtual dom object is just plain js object, which is totally reflecting some real dom element.
  2. Yes, you're right. Compare two js objects(virtual dom) is much more cheaper than comparing two dom elements.
  3. React uses complex O(n) algorithm to compare two trees of virtual dom. You shouldn't really think about that, it's about going deep to mathematics issues.
Amusement answered 22/9, 2017 at 4:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.