How to Call Reactdom Render Again
Introduction#
The ReactDOM library is non often talked about when working with React, still, Information technology is vital for any React developer to know how ReactDOM.render is used to inject our React code into the DOM. Information technology is also expert to get a brief idea of how it works nether the hood, and so we can write better code to accommodate the compages.
According to the React docs,
The
react-dom
package provides DOM-specific methods that can be used at the top level of your app and equally an escape hatch to go exterior of the React model if yous need to.
What You Will Learn#
By the stop of this blog mail service, you will hopefully know more about:
-
How React interacts with the DOM & Virtual DOM
-
The Reconciliation Process & React'due south Fiber Compages
-
Uses of
React.render()
& Best Practices -
Other ReactDOM methods
Prerequisites - What Yous Need To Know#
This blog post presents an overview of the ReactDOM library. Since it involves some core ReactJS concepts, it is better to be familiar with the library and how it works.
Even if you don't accept a deep agreement of React, this blog mail service can help demystify a lot of concepts related to rendering on the DOM.
Before moving to ReactDOM, let's take a brief look at the Document Object Model.
What is the DOM?#
The Document Object Model (DOM) is a code representation of all the webpages that you see on the internet. Every element, such every bit a push button or image that you lot see on the web-folio is a part of a hierarchy of various elements within a tree construction. This means each element (except the root element) is a child of another element. This construction enables yous to easily interface your JavaScript lawmaking with HTML to create highly powerful and dynamic web applications.
The Virtual DOM#
The way that web developers ordinarily work with the DOM to develop interactive websites, is by finding a DOM node and making the required changes to it, such as changing an attribute or adding a child node.
However, for highly dynamic web applications where the DOM needs to exist updated frequently, applying these required changes can be a slow process, as the browser ultimately has to update the entire DOM every time. To combat this trouble, React works with a Virtual DOM, which is just a representation of the actual DOM that is used behind the scenes to optimize the update process.
When a React element is updated, ReactDOM firstly updates the Virtual DOM. After that, the difference between the actual DOM and the Virtual DOM is calculated, and only the unique part. This means that the whole DOM does not need to be updated every unmarried time.
This process, too known as "reconciliation", is one of the things that helps us to build blazing fast Single Pages Applications (SPAs) with React.
react-dom#
ReactDOM is a package that provides methods that can exist used to interact with the DOM, which is needed to insert or update React elements. It provides many helper functions such as:
-
return()
-
hydrate()
-
unmountComponentAtNode()
-
findDOMNode()
-
createPortal()
And more than...
Most of the time when building Single Page Applications (such as with create-react-app), we normally create a single DOM container and call the render method in one case to initialize our React application. Since this method is always used when working with React, learning about the working of ReactDOM.render tin can greatly benefit us every bit React developers.
render()#
The render method tin be called the primary gateway betwixt React and the DOM.
Let's say you have defined a React element (<Calculator />
), besides as a DOM node to deed as a container for that element (div with the ID of "container"). Now, you tin can employ ReactDOM.render to return the element within that container using the syntax given below:
ReactDOM.return(<
Reckoner
/>, certificate.querySelector("#container"))
🔹 Annotation: If the Figurer component has already been mounted in the div element, calling this again volition but update the DOM based on the difference betwixt the components.
The statement above returns a reference to the component that yous take created. If it is a functional component, information technology returns null.
❕ The render value of render
is considered legacy every bit it may not be useful when futurity versions of React render components asynchronously.
Parameters:
-
React element
-
Selected DOM Node
-
Callback part (optional)
🔹 Note: ReactDOM.render requires a React element as the kickoff argument. React elements are generated through React.createElement. Therefore, yous may utilize that syntax or merely invoke a JSX estimation of the component to go the parameters in the right format for the arguments. Using React.createElement, our code can be modified to look like this:
ReactDOM.return(
React.createElement(Calculator)
, document.querySelector("#container"))
Tree Structure of React Elements:#
React elements are defined in a tree construction. This means each chemical element is essentially a child of another React element. However, for the root element, we need to create an chemical element (DOM Node) in our HTML code to act equally a container for our React element tree, which can be accessed via ReactDOM.render.
For a better agreement, the figure below defines an case React component tree:

In the higher up diagram, nosotros tin can meet that <Figurer />
is our root React chemical element, which is rendered into the container div within the HTML lawmaking.
Breaking information technology down further, the <Calculator />
element has two children, <Brandish />
and <KeyPad /
>. Similarly, <KeyPad />
is cleaved down into <NumKeys />
, <FunctionalKeys />
and <Operators />
.
This is what those components volition look similar in lawmaking:
Reconciliation & The React Fiber Architecture:#
⬛ The information in this section is not required to know to utilize React. The learning outcome of this section is to understand briefly the inner workings of React and it'south architecture, and to demystify the black box that is the reconciliation procedure. Information technology tin be benign to you if you plan to contribute to the library.
As defined above, the reconciliation process is when the React virtual DOM (AKA the tree of React elements) is checked confronting the bodily DOM, and merely the necessary updates are reflected.
In the previous versions of React, a linear synchronous approach was used to update the DOM. It became obvious very rapidly that this can greatly slow downwards our UI updates, negating the whole reason why reconciliation exists in the commencement place.
In React 16, the squad re-wrote major parts of the reconciliation algorithm to make it possible to update the DOM asynchronously. This is possible because of the Fiber compages which lies at the core of the new implementation.
Cobweb works in ii phases,
-
Reconciliation Phase
-
Commit Stage
Reconciliation (Render) Phase:#
This stage is triggered when a component is updated through country or props. Therefore, the standard React protocol is followed, where a component is updated and lifecycle hooks are called, after which the DOM nodes that need to be updated are calculated. In Fiber, these activities are termed as "work".
Earlier React xvi, having multiple work tasks could make our user interface wait and experience sluggish considering a recursive arroyo was used with the phone call stack. The problem with recursion is, that the procedure but stops when the call stack is empty, which tin can result in higher time complexity.
As more work is performed, more computational resources are utilized. The updated architecture utilizes the Linked List Data Structure within its algorithm to handle updates. This, used in conjunction with the requestIdleCallback()
function provided by newer browsers makes it possible to perform asynchronous tasks (or work) more efficiently.
Each "work" unit is represented by a Fiber Node. The algorithm starts from the top of the Fiber Node Tree and skips nodes until information technology reaches the one which was updated. Then information technology performs the required work and moves up the tree until all the required work is performed.
Commit Phase:#
During the commit phase, the algorithm start calls the required lifecycle methods before updating or unmounting a component. Then, it performs the actual work, that is, inserting, updating or deleting a node in the DOM. Finally, it calls the post-mutation lifecycle methods componentDidMount
and componentDidUpdate
.
Along with this, React likewise activates the Cobweb Node Tree that was generated in the previous phase. Doing this ensures synchronization between the tree of React elements and the DOM, as React knows what the current status of the Virtual DOM is.
Whew... notwithstanding abstract, we at present have a faint idea of how the reconciliation process works backside the scenes.
Using ReactDOM.render#
Usage in Unmarried Page Applications:#
Let's move back to the practical side of things, and discuss how we tin use ReactDOM.render in different scenarios.
Assuming we are working with a Single Page Application, we will only need to instantiate the root chemical element (normally App.jsx) at a single location in the DOM. Therefore, oftentimes the lone index.html file is not even touched at all.
All we need to practice is create a container, and render our React root element to it, as described in a higher place in the Reckoner example.
Integrating the React Component tree in whatsoever website:#
We can as well use ReactDOM.render to integrate React in a different application. This is why we call React a library, not a framework. You can use it as little every bit possible or every bit much as possible, as information technology completely depends on your employ-case.
We can create a wrapper function for our React module. All the required props can be passed to the office, and sent downward to the component which is rendered through ReactDOM.render, but like it would be for a single folio application.
It is important to export the office, as we volition need to phone call information technology within our JavaScript code.
In the index.html file shown above, we are importing the script that renders our root React component, and then we phone call the office using manifestly JavaScript. We can also pass parameters, such equally props for our React component, through this office. It is better to initialize React components after the certificate has loaded.
Y'all can also utilize ReactDOM.render multiple times throughout the awarding. This means that if you are creating a new website, or modifying an existing website that does not use React yet, you tin can use ReactDOM.render to generate some pages using React, while others do not use the library.
Cleaning up React nodes:#
When yous unmount a React component from the DOM, it is of import to phone call unmountComponentAtNode() according to the syntax given beneath to ensure at that place are no retentiveness leaks.
ReactDOM.unmountComponentAtNode(
DOMContainer
)
🔘 Information technology is up to you lot, the developer, to decide when it is time for clean-up.
This is why the React team suggests using a wrapper for your React root elements. Doing this ensures that you lot can mount and unmount React nodes co-ordinate to the design of your website. For example, moving from 1 React page to another that uses separate React root elements, it is possible to integrate the wrapper API with the page transition, which can automatically unmount the component for y'all.
Similarly, you can too write the logic in your wrapper to unmount a React root component within the same page, every bit presently equally its work is done.
Updating a Component with ReactDOM.render():#
To update a component, you lot may phone call ReactDOM.render again for the aforementioned React chemical element and DOM node. Nonetheless, one thing that is important to note is that ReactDOM.render completely replaces all of your props each time this function is called.
This means, you must also pass all of the other required props to the element that yous are rendering, which tin can exist an issue. The reason for the props being replaced is considering React elements are immutable. The React team explains how you can create a wrapper to set the previous props again.
More ReactDOM methods:#
Although render()
is the well-nigh usually used ReactDOM method, at that place are a few more available at your disposal. Allow's have a expect at ii of those.
-
hydrate()
It is similar to render()
, however, it is used when rendering pages through Server Side Rendering (SSR). It integrates the necessary effect handlers and functions to the markup that has been generated.
-
createPortal()
Portals can be created to render a component outside of the React component tree of that specific component. This can be highly useful to generate elements somewhere unrelated on the page.
Conclusion#
To sum it up, ReactDOM acts as a powerful interface between our React component tree and the DOM. The most commonly used method from ReactDOM is render()
, which can exist used to connect entire React applications to the DOM.
Once the React chemical element and it's child tree have been inserted into the DOM, the reconciliation process handles everything related to updates. Due to this process, whenever we update a part of our component tree, but the changes in that part are reflected in the actual DOM, thereby saving the states a lot of actress computation.
React and ReactDOM provides powerful functions such as render()
that make it easy to create fast and snappy Single Page Applications through React, which makes React such a popular front-end development library.
More Resource#
-
ReactDOM - ReactJS Docs
-
Rendering Elements - ReactJS Docs
-
ReactDOM.render and the Superlative Level React API
-
ReactJS & React DOM - GeeksForGeeks
-
A journey through ReactDOM.render — An explanation of how React manages the DOM and state
-
Within Fiber: in-depth overview of the new reconciliation algorithm in React
-
Invoking ReactDom.Render() From Exterior of React
Source: https://www.newline.co/@KumailP/a-closer-look-at-reactdomrender-the-need-to-know-and-more--891fed64
0 Response to "How to Call Reactdom Render Again"
Post a Comment