Difference Between Hydration and Rendering in React

With the new release of React v17 on 22 October 2020, it appe# ars a lot of added features. Today our quest is to bring out the difference between Hydration and Rendering in React JS. Let me allow shedding light on this.
What is ReactDOM
Before anything else, you need to understand the ReactDOM well.
ReactDOM is a package that presents DOM-specific methods, which can be used at the topmost level of a web app to facilitate an efficient way of managing DOM components of the web page.
To apply the ReactDOM in any React web app you must import ReactDOM first from the react-dom package. Here is the process.
import ReactDOM from 'react-dom'
However, both the render() and hydrate() functions are the modules for
the react-DOM package.
Render()
ReactDOM. render (element, container [callback]).
The render() function is one of the most useful and important functions of
ReactDOM. it returns a reference to the component after rendering a React
element into the DOM in the provided container (or returns null for stateless
components).
If the React element was previously made into a container, this will update it and only mutate the DOM as needed to represent the most recent React element.
The optional callback will be executed after the component is made or modified if it is given.
Note that,
The contents of the container node you move in are controlled by ReactDOM.render(). When the method is first called, any current DOM elements are substituted.
For efficient notifications, later calls use React's DOM diffing algorithm.
The container node is not changed by ReactDOM.render() (only modifies the children of the container). It's possible to add a component to an existing DOM node without overwriting the children.
At the moment, ReactDOM.render() returns a reference to the root ReactComponent case.
However, since future versions of React can make components asynchronously in some cases, using this return value is outdated and should be avoided. Attaching a callback ref to the root element is the best way to get a reference to the root ReactComponent case.
Let me go through a simple program that helps you understand the implementation of rendering in ReactJS.
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import app from './App';
ReactDOM.render(< App name = "Ryo"/>,
document.GetElementById("root"));
and
App.js
import React {fragment} from 'react';
const App = (props) => (
<fragment>
<h1>Hello, {props.name} </h1>
</fragment>
)
export default App;
Above these simple implements of the render(), function will display
Hello, Ryo in your browser.
ReactDOM.render() is obsolete and is replaced in React v17. Instead, try hydrating().
Ref: ReactDOM render()
Hydrate()
ReactDOM. hydrate(element, container [callback])
This function is similar to render(), but it's used to hydrate a container whose HTML content is made by ReactDOMServer.
The hydrate() function is implemented while using server-side rendering. React will try to add event
listeners to the markup that already exists.
React assumes that the rendered content on the server and the client are similar.
It can cover up inconsistencies in text content, but mismatches should be treated as bugs and fixed.
React warns about hydration mismatches when in development mode. In the event of a mismatch, there are no assurances that the gaps in attributes will be patched up.
Since mismatches are uncommon in most applications, validating all markup would be prohibitively costly.
If the attribute or text content of a single element (for example, a
timestamp) is unavoidably different between the server and the client, you
may disable the alert by setting suppressHydrationWarning=true to the
element.
It's only good for one level and is meant to be an escape hatch.
Using it sparingly, React won't try to fix it unless it's text material, so it'll probably stay inconsistent until future occurrence.
Now, let’s see how the same example works for Server Side Rendering
using the hydrate() function. Before that, you need to create the server file
which basically renders the HTML, and that server-rendered HTML will
hydrate at the client side. Here you go.
import express from 'express';
import path from 'path';
import React from 'react';
import ReactDOMServer from 'react-dom/Server';
import Hello from './public/component/Hello';
const app = express()
app.use('/static', express.static(path,resolve(_dirname,
'public')))
app.get('/', (req, res) => {
const name = 'Ryo is testing SSR'
const component = ReactDOMServer.renderingTString(<Hello name
= {name} />)
res.send(component)
})
app.listen(3000, () => {
console.log("The Server is running on port: 3000");
})
and now you can test the app through SSR.
import React from 'react';
const Hello = (props) => {
<React.fragment>
<h1>Hello, {props.name}</h1>
</React.fragment>
}
export default Hello;
and
import React from 'react';
import ReactDOM from 'react-dom';
import Hello from './component/Hello';
ReactDOM.hydrate(
<Hello name = {name}/>,
document.GetElementById("root")
)
Now your browser should display it as Hello, Ryo is testing SSR
You can do a two-pass rendering if you need to render anything differently on the server and the client.
A state variable like this can be read by components that make something different for the client. ComponentDidMount will allow you to set state.isClient to real().
This way, the first render pass would render the same content as the server, preventing mismatches, but a second pass will happen synchronously after hydration.
Since your components must be rendered twice, this method will slow them down, so it should be used with caution.
Remember to consider the user's experience when using sluggish connections.
Ref: ReactDOM hydrate()
Since the JavaScript code can load after the initial HTML render, the transition may be jarring if you render anything different in the client-only pass.
However, if done correctly, rendering a "shell" of the application on the server and just showing some of the extra widgets on the client can be helpful.
Refer to this article to learn how to do it without having markup mismatch problems, you can make a reference to the already discussed paragraph.
There are few more API-containing methods available in the ReactDOM package. They are worth discussing.
unmountComponentAtNode()
This function cleans up the event handlers and state of a mounted React node in the DOM.
This role does not affect if no part has been placed in the container.
If a part was unmounted, this method returns true; otherwise, it returns false.
Syntax of this function is as follows:
ReactDOM.unmountComponentAtNode(container)
Ref: ReactDOM unmountComponentAtNode()
findDOMNode()
Note: findDOMNode is a way to get to the DOM node underneath. Since it pierces the component abstraction, using this escape hatch is generally discouraged. In StrictMode, it is no longer supported.
Syntax of this function is as follows:
ReactDOM.findDOMNode(component)
This function returns the corresponding native browser DOM element if this item has been mounted into the DOM.
This method can be used to read values from the DOM, such as type field values, and to calculate the DOM. In most instances, attaching a ref to the DOM node is preferable to using findDOMNode.
findDOMNode returns null when a component is rendered null or false.
FindDOMNode returns a text DOM node containing the value of a component when it renders to a string.
A component can now return a fragment with multiple children, in which case findDOMNode will return the DOM node corresponding to the first non-empty child as of React 16.
Note:
Only installed components are supported by findDOMNode (that is, components that have been placed in the DOM). An exception will be thrown if you try to call this on a component that hasn't been mounted yet (for example, calling findDOMNode() in render() on a component that hasn't been developed yet).
On function components, findDOMNode isn't an option.
Ref: ReactDOM findDOMNode
createPortal()
This function creates a gateway. Children can be made into a DOM node that resides beyond the hierarchy of the DOM component using portals.
Syntax of this function is as follows:
ReactDOM.createPortal(child, container)
Ref: ReactDOM createPortal()
Wrapping Up
As the article says both the render() and hydrate() function are part of the ReactDOM package, and these two functions To wrap it up, ReactDOM acts as a powerful interface between React Js component tree and the DOM.
The most usually used method from ReactDOM is render() and hydrate() which can be used to connect entire React applications to the client-side and server-side.
Despite having all the above differences both the render() and hydrate() method makes React js such a widely popular front-end development library.
Thanks for spending your time reading the whole article. I believe, I was able to make things clear to you. Any suggestion is heartily welcome.
