Hackforge Academy

Category: react

what is websocket how to use websocket in react

Published on 22 Apr 2026

Explanation

WebSocket is a protocol that enables real-time, two-way (full-duplex) communication between client and server over a single persistent connection without repeated HTTP requests.

Code:

// HTTP: request -> response ->
 connection closed
// WebSocket: client <-> server 
(connection stays open)

Explanation

WebSockets are used in real-time applications such as chat apps, live notifications, stock updates, multiplayer games, and live dashboards.

Code:

// Example real-time apps:
// Chat application
// Live sports score updates
// Online collaboration tools

Explanation

In React, you can create a WebSocket connection using the built-in WebSocket object inside useEffect to connect when the component loads.

Code:

import { useEffect } from "react";

function App() {
  useEffect(() => {
    const socket = new WebSocket(
"ws://localhost:8080/chat");

    socket.onopen = () => {
      console.log(
"Connected to WebSocket server");
    };

    return () => socket.close();
  }, []);

  return <h1>WebSocket Connected</h1>;
}

Explanation

You can receive messages from the WebSocket server using the onmessage event handler.

Code:

socket.onmessage = (event) => {
  console.log("Message from server:",
 event.data);
};

Explanation

You can send messages from React to the WebSocket server using the send() method.

Code:

socket.send("Hello from React client");

Explanation

Store WebSocket instance in useRef when sending messages from different functions inside the component. import { useEffect, useRef } from "react"; function App() { const socketRef = useRef(null); {{below_code}} }

Code:

useEffect(() => {
    socketRef.current = 
new WebSocket("ws://localhost:8080/chat");

    return () => 
socketRef.current.close();
  }, []);

  const sendMessage = () => {
    socketRef.current.send("Hello Server");
  };

  return <button onClick={sendMessage}>
Send</button>;

Explanation

React applications commonly use WebSockets with backend frameworks like Spring Boot or Node.js to build real-time chat or notification systems.

Code:

// Example architecture:
// React client <-> WebSocket server 
(Spring Boot / Node.js)

πŸš€ Learn Spring Boot with real-world projects

πŸ’‘ Build REST APIs step by step

🧠 Improve backend development skills

🎯 Get career-ready practical training

Join Our Free WhatsApp Community

Direct access to niche-specific mentors and peers on WhatsApp.

🐍

Python Community

Discuss Django, FastAPI, AI integration, and automation scripts with 15k+ developers.

Join Python Community
βš›οΈ

React Community

Master Next.js, Framer Motion, and State Management. Share your latest UI components.

Join React Community
β˜•

Java Community

Deep dives into Spring Boot, Microservices architecture, and high-performance backend ops.

Join Java Community