Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Whats the difference between React render and React-DOM render

Tags:

reactjs

EDITED because my original question was not worded right.

I'm trying to understand why ReactDOM is being used to render some HTML divs, and other rendering is done in React. Is there something I'm missing here?

An example from a React course I took recently, this is the code in one of the exercises that uses react-dom:

import React, {Component} from 'react'
import {render} from 'react-dom'

var Bookstore = [
  {"title":"Mr. Bean", "author":"Rowan Atkinson", "pages":200},
  {"title":"The only Bean", "author":"Chris Dowd", "pages":100},
  {"title":"IT crowd", "author":"Rich Ayando", "pages":50}
]


const Book = ({title, author, pages}) => {
  return (
    <section>
      <h1>{title}</h1>
      <h3>By {author}</h3>
      <p>{pages} pages</p>
    </section>
  )
}


const Library = ({bookstore}) => {
  return (
    <div>
      {bookstore.map(
        (book, i) => <Book key={i} title={book.title} author={book.author} pages={book.pages}/>
      )}
    </div>
  )
}


render(
  <div>
    <Library bookstore={Bookstore} />
  </div>,
  document.getElementById('root')
)

While another React file renders this way:

import React, {Component} from 'react'

export const Book = ({title="No title", author="No author", pages=0, freeBookmark}) => {
  return (
    <section>
      <h1>{title}</h1>
      <h3>By {author}</h3>
      <p>{pages} pages</p>
    </section>
  )
}
like image 434
longboardnode Avatar asked Aug 03 '26 03:08

longboardnode


1 Answers

What happens in the real DOM ?

Each time something in the DOM changes. Since DOM is represented as a tree structure, changes to the DOM is pretty quick but the changed element, and it’s children’s has to go through Reflow/Layout stage and then the changes have to be Re-painted which are slow. Therefore more the items to reflow/repaint, slower your app becomes.

To overcome this react uses virtual DOM

How virtual DOM helps?

it tries to minimize these two stages to get better performance. virtual means a representation of a UI is kept in memory and synced with the "real" DOM by a library such as ReactDOM.

Difference between render in the component & reactDOM.render ?

  • Render in the component is used to construct the virtual DOM.
  • reactDOM.render is used to attach the virtual DOM tree to the real DOM tree after the diffing algorithm detects the changes.
like image 86
Tarek Essam Avatar answered Aug 05 '26 13:08

Tarek Essam