I have started leaning React. render() method is used at two places:
ReactDOM.render( <
Test / > ,
document.getElementById('react-application')
);
class Test extends React.Component {
render() {
return ( <
div > Hello < /div>
)
}
}
What is the exact difference between these two render methods?
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With