Implementing Server-side Rendering with React.js
Tags: webdev, react, javascript, beginners
Published: 2023-01-30 09:03:59


![Implementing Server-side Rendering with React.js, blog by front-end developer Abu Hasan Rumi](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/64gnjkg3h3anelx4eznt.jpg)

React.js is one of the most popular JavaScript libraries for building user interfaces. With its ability to build reusable UI components and handle complex user interactions, it's no wonder that so many developers choose React.js for their web development projects. One of the challenges of building with React.js, however, is optimizing the performance of your application, especially when it comes to server-side rendering.

Server-side rendering (SSR) is a process of rendering a client-side JavaScript framework on the server, sending the HTML to the client, and then hydrating the application on the client side. This can help improve the performance of your application by reducing the amount of JavaScript that needs to be loaded and parsed by the client.

In this blog post, we'll go over how to implement SSR in a React.js application, step by step.


### Step 1: Set up your React.js project
The first step is to set up your React.js project. You can use Create React App, a popular tool for bootstrapping React.js applications, to get started quickly. Simply run the following command in your terminal:

```
npx create-react-app my-app
cd my-app
```


### Step 2: Install the necessary packages
Next, you'll need to install a few packages to help you with server-side rendering. Express.js is a popular choice for handling server-side rendering in React.js applications. You can install it by running the following command:

```
npm install express
```


### Step 3: Create a server.js file
In your project's root directory, create a file called server.js. This file will be responsible for rendering your React.js components on the server. Add the following code to your server.js file:

```
const express = require('express');
const React = require('react');
const ReactDOMServer = require('react-dom/server');
const App = require('./src/App').default;

const server = express();

server.get('/', (req, res) => {
  const html = ReactDOMServer.renderToString(<App />);
  res.send(`
    <!DOCTYPE html>
    <html>
      <head>
        <title>Server-side Rendering with React.js</title>
      </head>
      <body>
        <div id="root">${html}</div>
        <script src="/static/js/bundle.js"></script>
      </body>
    </html>
  `);
});

server.listen(3000, () => {
  console.log('Server is running on http://localhost:3000');
});
```


### Step 4: Modify your React.js component
Finally, you'll need to modify your React.js component to support server-side rendering. Add the following code to your App.js file:

```
import React from 'react';

class App extends React.Component {
state = {
data: [],
};

componentDidMount() {
fetch('https://api.example.com/data')
.then(res => res.json())
.then(data => this.setState({ data }));
}

render() {
const { data } = this.state;
return (
<div>
<h1>Welcome to the Server-side Rendered React App</h1>
{data.length ? (
<ul>
{data.map(item => (
<li key={item.id}>{item.title}</li>
))}
</ul>
) : (
<p>Loading data...</p>
)}
</div>
);
}
}

export default App;
```


### Step 5: Use ReactDOM.renderToString() to render the component on the server
Next, you'll need to use ReactDOM.renderToString() to render your component on the server. This method will take your component and return the HTML string representation of it. You can use this string in your server-side template to render the content on the initial request.

Here's an example of how to use ReactDOM.renderToString():

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


### Step 6: Send the HTML to the client
Finally, you'll need to send the HTML string to the client. You can do this by sending a response from your server with the HTML string as the body.

Here's an example of sending the HTML to the client:

```
app.get('/', (req, res) => {
const html = ReactDOM.renderToString(<App />);
res.send( <html> <head> <title>Server-side Rendered React App</title> </head> <body> <div id="root">${html}</div> <script src="bundle.js"></script> </body> </html> );
});
```


And that's it! You've successfully set up server-side rendering for your React.js application. With this setup, you can improve the performance and SEO of your React.js applications.