Home » Building Real-time Apps with React Server Components

Building Real-time Apps with React Server Components

0 comment 46 views
0

Frontend application has become the latest buzzword as it provides a suitable choice to inform the targeted audience about different products and services of the business. It is also beneficial in driving the sales and enhancing the brand recognition. To create a frontend application, you need to select a domain name to secure the website hosting. It is useful in keeping the site optimized and updated for different smart devices.

React Server Components happen to be the latest feature in React, which provides a suitable choice for the developers in writing the components, which are rendered onto the server, after which they are streamed to the client directly. By choosing different React Server components, the developers will be capable of creating high-performance web apps with faster loads and an improved user experience.

Regular server-side rendering within React includes sending the HTML page to the potential client from the server. However, it can prove to be inefficient and slow. Choosing React Server components is notable in this aspect as it sends only those components to the clients, which need to be rendered. Thus, it helps to decrease the total data count, which should be transferred. React Server components offer improved support for collaborative editing and real-time updates. As the components get rendered onto the server, if changes are made on the server, they will be reflected for other users without the need for a full page refresh.

In this write-up, we will talk how HarperDB and socket.io can be used to create a real-time and full stack front app. If you opt for HTTP requests, the server will not be able to push the data to the potential client in real time. However, if you choose Socket.io, the server will gain success in pushing the information in real time to the potential client regarding certain events that occur on the server.

About Socket.io

Socket.IO provides a suitable choice to the server for frontend development in pushing the information to the potential clients in the real time. Thus, potential clients do not need to carry the hassle of creating several polling AJAX calls to find out whether certain events are happening on the server. Socket.IO lends a helping hand in creating real-time apps.

Tips to set up the folders

  • You should begin a new project within the text editor you want and develop two different folders at the root, known as server and client.
  • Now, we will develop the frontend React app within the client folder, and the Node/Express backend is present within the server folder.
  • In the next step, you should open the terminal present at the project’s root.
  • Then, you need to install React within the client directory.

$ npx create-react-app client

With the installation of React, you should change the directories present on the client folder after which you should consider installing the below dependencies.

$ cd client

$ npm i react-router-dom socket.io-client

With react-router-dom, you will be capable of setting different routes to various React components, thereby creating various pages. Socket-io-client happens to be the socket.io’s client version, which provides the suitable choice to emit different events to the specific server. As soon as the server receives it, you can make the right use of socket.io’s server version to send certain messages to potential users.

Booting the React App

You should execute the below command within the client directory to ensure that everything is working properly:

$ npm start

Setting HarperDB

  • In the beginning, you need to come up with the account using HarperDB.
  • After this, you should develop the HarperDB cloud instance.
  • Then, you should choose a cloud instance.
  • Also, you need to select the specific cloud service provider.
  • Here, you should give a name to the cloud instance, after which you should develop the instance credentials.
  • Once you ensure that all the details are accurate, you should come up with an instance.

 Tips to Create a Join Room Page

To begin with, we will discuss the steps to creating an HTML form and adding the styles:

Creating a file at src/pages/home/index.js

 In this step, you will be adding basic styling to the application through CSS modules. Hence, you should develop the below file. Check out!

 src/pages/home/styles.module.css.

Here are the steps to create the basic HTML form:

// client/src/pages/home/index.js

import styles from ‘./styles.module.css’;

const Home = () => {

  return (

<div className={styles.container}>

   <div className={styles.formContainer}>

        <h1>{`<>DevRooms</>`}</h1>

     <input className={styles.input} placeholder=’Username…’ />

     <select className={styles.input}>

          <option>– Select Room –</option>

          <option value=’javascript’>JavaScript</option>

          <option value=’node’>Node</option>

          <option value=’express’>Express</option>

          <option value=’react’>React</option>

        </select>

     <button className=’btn btn-secondary’>Join Room</button>

   </div>

</div>

  );

};

export default Home;

It is a simple text input to collect the specific user name along with a select dropdown with a certain default option for the potential user to choose the chat room. The specific component is imported within APp.js, after which the route is set up for the specific component through the react0router-dom package.

// client/src/App.js

import ‘./App.css’;

import { BrowserRouter as Router, Routes, Route } from’react-router-dom’;

import Home from ‘./pages/home’;

function App() {

  return (

<Router>

   <div className=’App’>

     <Routes>

          <Route path=’/’ element={<Home />} />

        </Routes>

   </div>

</Router>

  );

}

export default App;

In this section, we will add certain base styles so that the application looks appealing.

/* client/src/App.css */

html * {

  font-family: Arial;

  box-sizing: border-box;

}

body {

  margin: 0;

  padding: 0;

  overflow: hidden;

  background: rgb(63, 73, 204);

}

::-webkit-scrollbar {

  width: 20px;

}

::-webkit-scrollbar-track {

  background-color: transparent;

}

::-webkit-scrollbar-thumb {

  background-color: #d6dee1;

  border-radius: 20px;

  border: 6px solid transparent;

  background-clip: content-box;

}

::-webkit-scrollbar-thumb:hover {

  background-color: #a8bbbf;

}

.btn {

  padding: 14px 14px;

  border-radius: 6px;

  font-weight: bold;

  font-size: 1.1rem;

  cursor: pointer;

  border: none;

}

.btn-outline {

  color: rgb(153, 217, 234);

  border: 1px solid rgb(153, 217, 234);

  background: rgb(63, 73, 204);

}

.btn-primary {

  background: rgb(153, 217, 234);

  color: rgb(0, 24, 111);

}

.btn-secondary {

  background: rgb(0, 24, 111);

  color: #fff;

}

 Tips to add functionality onto the Join Room form

It is important to create the state to store the username along with the room values. Now, we will execute the command to create the state for Nextjs app development, set the socket in App.js, and pass certain variables as props to the <Home/> component.

// client/src/App.js

import ‘./App.css’;

import { useState } from ‘react’; // Add this

import { BrowserRouter as Router, Routes, Route } from ‘react-router-dom’;

import io from ‘socket.io-client’; // Add this

import Home from ‘./pages/home’;

const socket = io.connect(‘http://localhost:4000’); //

function App() {

  const [username, setUsername] = useState(”); // Add this

  const [room, setRoom] = useState(”); // Add this

  return (

<Router>

   <div className=’App’>

     <Routes>

          <Route

            path=’/’

            element={

              <Home

                username={username} // Add this

                setUsername={setUsername} // Add this

                room={room} // Add this

                setRoom={setRoom} // Add this

                socket={socket} // Add this

              />

            }

          />

        </Routes>

   </div>

</Router>

  );

}

export default App;

After collecting the data, the potential user enters, and you will create the joinRoom() callback function as the potential user tapss on Join Room button.

// client/src/pages/home/index.js

// …

const Home = ({ username, setUsername, room, setRoom, socket }) => {

  // Add this

  const joinRoom = () => {

if (room !== ” && username !== ”) {

   socket.emit(‘join_room’, { username, room });

}

  };

  return (

<div className={styles.container}>

   // …

     <button

          className=’btn btn-secondary’

          style={{ width: ‘100%’ }}

          onClick={joinRoom} // Add this

     >

          Join Room

        </button>

   // …

</div>

  );

};

export default Home;

To complete home page part, it is necessary to add the redirect at joinRoom() function to redirect the potential user to the specific /chat page:

// client/src/pages/home/index.js

// …

import { useNavigate } from ‘react-router-dom’; // Add this

const Home = ({ username, setUsername, room, setRoom, socket }) => {

  const navigate = useNavigate(); // Add this

  const joinRoom = () => {

if (room !== ” && username !== ”) {

   socket.emit(‘join_room’, { username, room });

}

// Redirect to /chat

navigate(‘/chat’, { replace: true }); // Add this

  };

 // …

0

Trending Post

Recent Post