Menu
Component nesting in React

Guide for a Server-Side Rendering in ReactJs

Shivangi Rajde 11 months ago 0 223

React is a powerful JavaScript library that allows developers to build complex and interactive user interfaces. However, when it comes to rendering these interfaces on the server, React can be a bit tricky. This is where server-side rendering (SSR) comes in. SSR is the process of rendering a web page on the server and sending it to the client as HTML, rather than relying on client-side JavaScript to render the page.

In this article, we will provide a step-by-step guide for building a server-side rendering React app. Let’s understand some concepts before getting started with the steps.

What is server-side rendering (SSR) in React?

Server-side rendering (SSR) is the process of rendering a web page on the server and sending the fully-rendered HTML to the client, rather than relying on client-side JavaScript to render the page. In the context of React, SSR allows the initial page load to include a fully-rendered HTML page, rather than just a barebones HTML file and a JavaScript bundle.

In a typical React SSR app, the server receives a request for a particular URL, and then renders the corresponding React components on the server. The server generates an HTML string that includes the fully-rendered React components and sends this HTML string to the client as the initial page response. Once the initial page is loaded, the client-side JavaScript bundle is then downloaded and executed, and takes over the rendering process from that point on.

One of the advantages of SSR is that it can result in a faster initial page load since the browser doesn’t need to wait for the JavaScript bundle to be downloaded and executed before the page can be displayed. This can result in a faster-perceived performance, especially for users with slower internet connections or less powerful devices. Additionally, SSR can be more SEO-friendly, since search engines are able to crawl and index fully-rendered HTML pages.

However, there are also some potential downsides to SSR. One issue is that it can be more complex to set up and maintain than client-side rendering since the server needs to be configured to handle the rendering process. Additionally, SSR can result in a higher server-side load, since the server needs to handle the rendering process for each request. This can potentially result in slower server response times, especially for high-traffic sites.

Overall, server-side rendering can be a powerful approach for building fast, SEO-friendly web apps, and can be a good choice for certain types of projects. However, it’s important to carefully consider the potential tradeoffs and to weigh the benefits against the added complexity and server-side load.

What is client-side rendering (CSR) in React?

Client-side rendering (CSR) is the process of rendering a web page using JavaScript on the client side (i.e., in the browser), rather than rendering the page on the server and sending it to the client as HTML. In the context of React, CSR refers to the default way that React apps are rendered, where the initial page load only includes a barebones HTML file and a JavaScript bundle, and the full page is then rendered by the client-side JavaScript code.

In a typical React CSR app, the browser downloads the JavaScript bundle, which contains all of the necessary code to render the app. Once the bundle is downloaded, the JavaScript code is executed in the browser, which then takes over the rendering process. The JavaScript code creates a virtual DOM (a representation of the actual HTML DOM in memory), and then uses this virtual DOM to render the app. Any updates to the app are also handled by the client-side JavaScript code, which updates the virtual DOM and then updates the actual DOM to reflect the changes.

One of the advantages of CSR is that it allows for a more dynamic and interactive user experience since updates can be made to the app without requiring a full page refresh. This can result in a faster and more responsive app, since only the necessary parts of the page need to be updated, rather than the entire page.

However, there are also some potential downsides to CSR. One issue is that the initial page load can be slower since the browser needs to download the JavaScript bundle and execute it before the app can be rendered. This can result in slower perceived performance for users with slower internet connections or less powerful devices. Another issue is that CSR can be less SEO-friendly, since search engines may have difficulty crawling and indexing client-side rendered pages. This can potentially impact the visibility of the app in search results.

Overall, client-side rendering is a powerful approach to building dynamic and interactive web apps and is the default rendering method for React apps. However, it’s important to consider the potential downsides and tradeoffs when deciding on the best approach for a particular project.

Step-by-step guide for building a server-side rendering React app

Step 1: Create a React app

To get started, you need to create a new React app. You can do this using the Create React App tool, which provides a pre-configured setup for building React apps.

To create a new React app using Create React App, open a terminal window and run the following command:

npx create-react-app my-app

This will create a new React app called “my-app” in a new directory of the same name.

Step 2: Add server-side rendering

Next, we need to add server-side rendering to our app. There are several libraries available for this, but we will be using React’s built-in server-side rendering capabilities.

To do this, we need to create a new file in the root of our app called “server.js”. This file will contain the code for our server-side rendering.

In “server.js”, we need to import the necessary dependencies and create an instance of the express server:

const express = require('express');
const React = require('react');
const ReactDOMServer = require('react-dom/server');

const app = express();

Next, we need to define a route that will handle our server-side rendering. We will create a route for the homepage, but you can create routes for any page in your app:

app.get('/', (req, res) => {
  // Server-side rendering code goes here
});

Inside this route, we need to render our React app using ReactDOMServer.renderToString(). This method takes a React component and returns the HTML string representation of that component:

const App = require('./src/App').default;

const html = ReactDOMServer.renderToString(<App />);

Finally, we need to send the rendered HTML back to the client:

res.send(`
  <html>
    <head>
      <title>My App</title>
    </head>
    <body>
      <div id="root">${html}</div>
      <script src="/static/js/bundle.js"></script>
    </body>
  </html>
`);

This code sends back an HTML page that includes the rendered React app and a link to the client-side JavaScript bundle.

Step 3: Update the client-side code

Now that we have server-side rendering set up, we need to update our client-side code to handle the fact that the page has already been rendered on the server.

To do this, we need to use ReactDOM.hydrate() instead of ReactDOM.render(). This method takes a React component and attaches it to an existing HTML element on the page:

import ReactDOM from 'react-dom';
import App from './App';

ReactDOM.hydrate(<App />, document.getElementById('root'));

Step 4: Start the server

Finally, we need to start our server so that we can see our app in action.

To start the server, run the following command in your terminal:

node server.js

This will start the server and make your app available at http://localhost:3000.

Conclusion

In this article, we have provided a step-by-step guide for building a server-side rendering React app. By following these steps, you should now have a basic idea about Server side rendering in React app.

To read more about hooks refer to the links given below:
useEffect: The Effect Hook
useState: Managing State in React functional components

– Advertisement – BuzzMag Ad
Written By

Leave a Reply

Leave a Reply

Your email address will not be published. Required fields are marked *