nonopolarity
nonopolarity

Reputation: 151026

When we use JSX <div></div>, or React.createElement("div", ...), is this virtual DOM (element)?

When we use JSX

let el = <div></div>;

or

let el = React.createElement('div', ...);

(they are identical, AFAIK). Is el, or <div></div> virtual DOM (element), or does virtual DOM mean something else? So my question really is, is <div></div> what will become part of the virtual DOM? React.createElement() creates an object. Will this object become part of virtual DOM (tree)?

I am wondering if virtual DOM means the whole tree or the virtual document object model way of storing all the elements. When we say, ReactDOM.render(<Foo />, rootEl), it is rendering the virtual DOM elements into the virtual DOM tree and the actual DOM tree. (Just like let el = document.createElement() creates the actual DOM element, and document.body.appendChild(el) adds the DOM element to the DOM tree.) So <div></div> or React.createElement('div', ...) creates something that will become part of the virtual DOM.

Upvotes: 1

Views: 867

Answers (2)

Dan
Dan

Reputation: 10538

When you use React.createElement()†, you create a description of an element to be rendered:

> React.createElement('div', [], "Hello, world!");
{ '$$typeof': Symbol(react.element),
  type: 'div',
  key: null,
  ref: null,
  props: { children: 'Hello, world!' },
  _owner: null,
  _store: {} }

Each of these elements can, in turn, render other elements to form a tree.

When you pass a root node to ReactDOM.render() (and friends), ReactDOM will turn this description of elements into an initial render and insert it into the DOM.

When an update occurs in the tree, React will re-render all of its descendants (with a few exceptions) and, through a process called Reconciliation, React will diff the new version with the previous version it rendered. React will then take the diff and apply the operations required to turn the old DOM state into the next desired DOM state.

This in-memory store of a representation of the current state of DOM is what we mean when we talk about the "Virtual DOM".

Using React.createElement() is not what I would personally consider Virtual DOM as it's not actually made part of the Virtual DOM model until it is passed to render() (either directly or by being part of the tree that is passed).

You can find information about diffing on the React page for Reconciliation and there's a deeper dive on the page about Optimizing Performance.


Footnotes:

React.createElement('div', [], 'Hello, world!'); is identical to <div>Hello, world!</div>. Your compiler will compile the JSX into a series of React.createElement calls.

Upvotes: 1

Mauricio Fow
Mauricio Fow

Reputation: 46

They are the same, but using JSX is more readable when you have a lot of elements. That's why it's called syntactic sugar, it helps you to have a better structured code that you can easily read.

Upvotes: 0

Related Questions