Shubham
Shubham

Reputation: 1191

React Virtual Dom under the hood

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 -

Any video lecture for that would be really appreciated.

Upvotes: 6

Views: 985

Answers (2)

Matthew Barbara
Matthew Barbara

Reputation: 3962

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

Upvotes: 2

player66
player66

Reputation: 1

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.

Upvotes: 0

Related Questions