How to Call Reactdom Render Again

Introduction#

The ReactDOM library is not often talked about when working with React, however, It is vital for any React programmer to know how ReactDOM.render is used to inject our React lawmaking into the DOM. It is likewise good to get a brief idea of how information technology works under the hood, and so nosotros tin can write better code to accommodate the architecture.

According to the React docs,

The react-dom bundle provides DOM-specific methods that tin be used at the acme level of your app and as an escape hatch to get exterior of the React model if y'all demand to.

What Yous Will Larn#

By the finish of this blog post, you will hopefully know more about:

  • How React interacts with the DOM & Virtual DOM

  • The Reconciliation Procedure & React's Fiber Architecture

  • Uses of React.render() & All-time Practices

  • Other ReactDOM methods

Prerequisites - What Yous Demand To Know#

This web log post presents an overview of the ReactDOM library. Since information technology involves some cadre ReactJS concepts, it is meliorate to be familiar with the library and how it works.

Even if you don't have a deep understanding of React, this weblog mail service can help demystify a lot of concepts related to rendering on the DOM.

Earlier moving to ReactDOM, let's take a brief wait at the Certificate Object Model.

What is the DOM?#

The Certificate Object Model (DOM) is a code representation of all the webpages that you run into on the internet. Every element, such equally a button or image that you see on the web-page is a part of a bureaucracy of diverse elements within a tree structure. This ways each element (except the root element) is a child of another element. This structure enables you to hands interface your JavaScript code with HTML to create highly powerful and dynamic web applications.

The Virtual DOM#

The way that web developers usually work with the DOM to develop interactive websites, is past finding a DOM node and making the required changes to it, such as changing an attribute or calculation a child node.

Withal, for highly dynamic web applications where the DOM needs to be updated oftentimes, applying these required changes can be a slow process, every bit the browser ultimately has to update the entire DOM every time. To combat this trouble, React works with a Virtual DOM, which is simply a representation of the bodily DOM that is used backside the scenes to optimize the update process.

When a React element is updated, ReactDOM firstly updates the Virtual DOM. Afterward that, the departure between the bodily DOM and the Virtual DOM is calculated, and only the unique part. This means that the whole DOM does not need to exist updated every single time.

This process, besides known as "reconciliation", is one of the things that helps usa to build blazing fast Single Pages Applications (SPAs) with React.

react-dom#

ReactDOM is a package that provides methods that tin be used to interact with the DOM, which is needed to insert or update React elements. Information technology provides many helper functions such as:

  1. render()

  2. hydrate()

  3. unmountComponentAtNode()

  4. findDOMNode()

  5. createPortal()

And more...


Most of the fourth dimension when edifice Unmarried Page Applications (such as with create-react-app), nosotros normally create a single DOM container and call the return method once to initialize our React application. Since this method is always used when working with React, learning almost the working of ReactDOM.return can greatly benefit us as React developers.

return()#

The render method tin can be chosen the primary gateway betwixt React and the DOM.

Let'due south say yous have defined a React element (<Computer />), as well every bit a DOM node to act equally a container for that element (div with the ID of "container"). Now, you tin can apply ReactDOM.render to return the element within that container using the syntax given beneath:

ReactDOM.render(< Calculator />, document.querySelector("#container"))

🔹 Note: If the Estimator component has already been mounted in the div chemical element, calling this again will just update the DOM based on the difference between the components.

The argument to a higher place returns a reference to the component that you have created. If it is a functional component, it returns null.

❕ The return value of return is considered legacy as it may not be useful when future versions of React return components asynchronously.

Parameters:

  • React element

  • Selected DOM Node

  • Callback function (optional)

🔹 Note: ReactDOM.render requires a React element as the first argument. React elements are generated through React.createElement. Therefore, y'all may use that syntax or only invoke a JSX interpretation of the component to get the parameters in the correct format for the arguments. Using React.createElement, our code tin can be modified to expect like this:


ReactDOM.render( React.createElement(Calculator) , document.querySelector("#container"))

Tree Structure of React Elements:#

React elements are divers in a tree structure. This means each element is substantially 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 as a container for our React element tree, which can be accessed via ReactDOM.render.

For a better agreement, the effigy below defines an example React component tree:

In the higher up diagram, nosotros tin meet that <Calculator /> is our root React element, which is rendered into the container div within the HTML code.

Breaking it downwards further, the <Calculator /> element has two children, <Display /> and <KeyPad / >. Similarly, <KeyPad /> is broken downwards into <NumKeys /> , <FunctionalKeys /> and <Operators /> .

This is what those components will look like in code:

Reconciliation & The React Fiber Architecture:#

⬛ The information in this section is not required to know to use React. The learning outcome of this section is to understand briefly the inner workings of React and information technology'south architecture, and to demystify the blackness box that is the reconciliation process. Information technology tin be beneficial to you if you lot programme 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 actual DOM, and only 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 quickly that this can profoundly slow down our UI updates, negating the whole reason why reconciliation exists in the first place.

In React xvi, the team re-wrote major parts of the reconciliation algorithm to brand it possible to update the DOM asynchronously. This is possible considering of the Fiber architecture which lies at the core of the new implementation.

Fiber works in two phases,

  • Reconciliation Phase

  • Commit Stage

Reconciliation (Return) Phase:#

This stage is triggered when a component is updated through state or props. Therefore, the standard React protocol is followed, where a component is updated and lifecycle hooks are chosen, after which the DOM nodes that need to be updated are calculated. In Fiber, these activities are termed every bit "piece of work".

Before React 16, having multiple piece of work tasks could make our user interface expect and feel sluggish because a recursive approach was used with the telephone call stack. The problem with recursion is, that the process only stops when the call stack is empty, which can issue in higher time complication.

Equally more work is performed, more computational resources are utilized. The updated architecture utilizes the Linked List Information Structure within its algorithm to handle updates. This, used in conjunction with the requestIdleCallback() office provided by newer browsers makes it possible to perform asynchronous tasks (or work) more than 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 it reaches the one which was updated. And then it performs the required work and moves upwards the tree until all the required work is performed.

Commit Phase:#

During the commit phase, the algorithm showtime calls the required lifecycle methods before updating or unmounting a component. Then, it performs the bodily work, that is, inserting, updating or deleting a node in the DOM. Finally, it calls the mail service-mutation lifecycle methods componentDidMount and componentDidUpdate.

Along with this, React as well activates the Fiber Node Tree that was generated in the previous stage. Doing this ensures synchronization between the tree of React elements and the DOM, equally React knows what the current status of the Virtual DOM is.

Whew... still abstract, we now have a faint idea of how the reconciliation process works backside the scenes.

Using ReactDOM.return#

Usage in Single Folio Applications:#

Let'southward move back to the practical side of things, and discuss how we can use ReactDOM.render in different scenarios.

Assuming we are working with a Single Page Application, nosotros will only need to instantiate the root chemical element (usually App.jsx) at a single location in the DOM. Therefore, often the lonely alphabetize.html file is not even touched at all.

All we need to do is create a container, and return our React root chemical element to it, as described in a higher place in the Calculator example.

Integrating the React Component tree in any website:#

Nosotros can also use ReactDOM.return to integrate React in a different application. This is why we call React a library, non a framework. Y'all can utilise it as little as possible or as much as possible, as it completely depends on your use-case.

We can create a wrapper function for our React module. All the required props tin can be passed to the function, and sent down to the component which is rendered through ReactDOM.render, just like it would exist for a unmarried page application.

It is important to export the function, as we will demand 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 role using plain JavaScript. We tin also pass parameters, such equally props for our React component, through this function. It is amend to initialize React components afterward the certificate has loaded.

You tin can likewise use ReactDOM.render multiple times throughout the awarding. This ways that if you are creating a new website, or modifying an existing website that does not use React still, you lot tin can employ ReactDOM.return to generate some pages using React, while others do not use the library.

Cleaning upwardly React nodes:#

When yous unmount a React component from the DOM, it is important to phone call unmountComponentAtNode() according to the syntax given beneath to ensure there are no memory leaks.

ReactDOM.unmountComponentAtNode( DOMContainer )

🔘 Information technology is up to you, the programmer, to determine when information technology is time for clean-upwards.

This is why the React team suggests using a wrapper for your React root elements. Doing this ensures that you can mountain and unmount React nodes co-ordinate to the design of your website. For case, moving from i React page to some other that uses carve up React root elements, it is possible to integrate the wrapper API with the page transition, which can automatically unmount the component for you.

Similarly, you lot tin likewise write the logic in your wrapper to unmount a React root component within the aforementioned page, as before long every bit its work is done.

Updating a Component with ReactDOM.render():#

To update a component, you may call ReactDOM.render over again for the aforementioned React element and DOM node. However, one affair that is of import to note is that ReactDOM.render completely replaces all of your props each time this role is called.

This means, y'all must also pass all of the other required props to the element that you are rendering, which tin be an issue. The reason for the props being replaced is because React elements are immutable. The React team explains how y'all tin can create a wrapper to gear up the previous props again.

More ReactDOM methods:#

Although return() is the most commonly used ReactDOM method, there are a few more bachelor at your disposal. Permit'due south take a look at two of those.

  1. hydrate()

It is like to render(), however, it is used when rendering pages through Server Side Rendering (SSR). It integrates the necessary result handlers and functions to the markup that has been generated.

  1. createPortal()

Portals can be created to render a component outside of the React component tree of that specific component. This can exist highly useful to generate elements somewhere unrelated on the page.

Conclusion#

To sum it upwards, ReactDOM acts as a powerful interface between our React component tree and the DOM. The most normally used method from ReactDOM is render(), which tin can be used to connect entire React applications to the DOM.

In one case the React element and it's child tree have been inserted into the DOM, the reconciliation process handles everything related to updates. Due to this procedure, whenever we update a function of our component tree, but the changes in that role are reflected in the bodily DOM, thereby saving us a lot of extra computation.

React and ReactDOM provides powerful functions such as render() that brand it easy to create fast and snappy Single Page Applications through React, which makes React such a popular front-stop development library.

More Resources#

  • ReactDOM - ReactJS Docs

  • Rendering Elements - ReactJS Docs

  • ReactDOM.return and the Top Level React API

  • ReactJS & React DOM - GeeksForGeeks

  • A journey through ReactDOM.return — An explanation of how React manages the DOM and state

  • Inside Fiber: in-depth overview of the new reconciliation algorithm in React

  • Invoking ReactDom.Render() From Outside of React

canalesbatouth61.blogspot.com

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

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel