Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactDOM.render vs React Component render difference

Tags:

I have started leaning React. render() method is used at two places:

  1. With ReactDOM.render()
ReactDOM.render( <
  Test / > ,
  document.getElementById('react-application')
);
  1. Other is inside class which extends component.
class Test extends React.Component {
  render() {
    return ( <
      div > Hello < /div>
    )
  }
}

What is the exact difference between these two render methods?

like image 251
Priyanka Avatar asked Jan 22 '18 19:01

Priyanka


2 Answers

There are two separate render() methods in React. One is ReactDOM.render() and the other is Component.render().

Component.render()

A component's render() method takes no arguments and returns the corresponding React element tree for that component. Component.render() gets called when the props or the state of a component change and shouldComponentUpdate() returns true. Based on the new props and state a new element React element tree is returned from the Component.render() method.

ReactDOM.render()

The ReactDOM.render(element, container) method is a top-level API that takes a React element root of an element tree and a container DOM element as arguments. It then turns that passed React element into a corresponding DOM element (tree) and then mounts that element as a child in the container DOM element.

Before mounting any DOM elements to the container though, React performs a diff between the passed element tree and the currently mounted DOM to determine which of the DOM nodes in the currently mounted DOM have to be updated in order to match the newly passed element tree.

Read more about ReactDOM.render() here

like image 140
TheBaj Avatar answered Sep 28 '22 07:09

TheBaj


TLDR:

React creates a virtual DOM before adding (mounting) it into the actual browser DOM, before it is displayed. One of the two methods does the first action only, and the other does both.

component.render only creates the virtual DOM. It does not add it to the actual browser DOM.

ReactDOM.render does both. It creates (or updates) the virtual DOM, and then additionally adds it to the actual browser DOM.

like image 44
imagineerThat Avatar answered Sep 28 '22 06:09

imagineerThat