DEV Community

Cover image for A Beginner's Guide to Implementing WebSockets in React
SHaon
SHaon

Posted on

A Beginner's Guide to Implementing WebSockets in React

Are you ready to take your React applications to the next level of real-time interactivity? Say hello to WebSockets! In this beginner-friendly guide, we'll walk through the process of integrating WebSockets into your React projects. By the end, you'll have a solid understanding of how to establish a WebSocket connection and leverage its power for real-time communication between the client and server.

Understanding WebSockets

Before diving into implementation, let's grasp the concept of WebSockets. Unlike traditional HTTP requests, which follow a request-response model, WebSockets provide a persistent, full-duplex communication channel over a single TCP connection. This means both the client and server can send data to each other at any time, enabling real-time updates without the overhead of HTTP requests.

Setting Up Your React Project

First things first, make sure you have Node.js and npm installed on your machine. If not, head over to nodejs.org and follow the installation instructions.

Now, let's create a new React project using Create React App. Open your terminal and run the following commands:

npx create-react-app websocket-demo
cd websocket-demo

Once your project is set up, navigate into the project directory and install a WebSocket library. For this tutorial, we'll use websocket:

npm install websocket

Establishing a WebSocket Connection

Now that our project is ready, let's establish a WebSocket connection. Create a new file named WebSocketComponent.js in the src directory of your project. Here's a basic implementation:

// App.js

import React from 'react';
import WebSocketComponent from './WebSocketComponent';

function App() {
  return (
    <div className="App">
      <WebSocketComponent />
    </div>
  );
}

export default App;

Enter fullscreen mode Exit fullscreen mode
// WebSocketComponent.js

import React, { useEffect, useState } from 'react';

const WebSocketComponent = () => {
  const [message, setMessage] = useState('');

  useEffect(() => {
    // Establishing a WebSocket connection
    const socket = new WebSocket('ws://localhost:3000');

    // Event listener for connection open
    socket.onopen = () => {
      console.log('WebSocket connection established.');
    };

    // Event listener for incoming messages
    socket.onmessage = (event) => {
      setMessage(event.data);
    };

    // Cleanup function to close the socket on component unmount
    return () => {
      socket.close();
    };
  }, []);

  return (
    <div>
      <h1>WebSocket Demo</h1>
      <p>Received message: {message}</p>
    </div>
  );
};

export default WebSocketComponent;

Enter fullscreen mode Exit fullscreen mode

Interacting with the WebSocket

In the useEffect hook, we create a new WebSocket instance and define event handlers for onopen and onmessage events. When the connection is established, we log a message to the console. When a message is received from the server, we log its content.

This code assumes you have a WebSocket server running on ws://localhost:3000, which sends messages to the client. Replace 'ws://localhost:3000' with your actual WebSocket server URL.

Top comments (1)

Collapse
 
kouwenhoven profile image
Ester

I miss the set up from the websockets server in this guide