Real-Time Data Streaming in React with Server-Sent Events (SSE)

Sandip DebSandip Deb
4 min read

In the world of modern web apps, real-time updates have become a necessity. Whether it's live notifications, chat applications, or dashboards, real-time data enriches user experience.

In this post, I’ll walk you through implementing Server-Sent Events (SSE) in a React app to handle real-time data streaming effectively.


What are Server-Sent Events (SSE)?

SSE is a browser-based API allowing servers to push client updates over HTTP in a one-way communication channel. Unlike WebSockets, SSE is lightweight, easy to use, and works seamlessly with HTTP/1.1.

How SSE Works

  1. The client establishes a persistent connection to the server using EventSource.

  2. The server pushes data as a stream to the client in the form of text-based events.

  3. The client listens for these updates and processes them in real time.


When to Use SSE?

SSE is perfect for:

  • Live notifications

  • Streaming logs

  • Real-time dashboards

  • Event updates (e.g., ticketing systems)


Building a React App with SSE

1. The Problem

Let’s say we want to create a real-time patient diagnosis stream based on live server updates. The server sends the following data:

  • Patient’s diagnosis list

  • Suggestions based on the diagnosis

  • Patient’s gender details

Our goal: Build a React component to handle this live stream of data.


2. The Implementation

Here’s how we implement SSE in React:

Step 1: Set Up State and Ref

We’ll use useState to manage diagnoses and gender details, and useRef to handle scrolling.

import { useEffect, useRef, useState } from "react";

const SSE = () => {
  const [diagnoses, setDiagnoses] = useState([]);
  const [genderDetails, setGenderDetails] = useState({});
  const containerRef = useRef(null);

Step 2: Connect to the SSE Endpoint

We use the EventSource API to establish a connection to the SSE endpoint.

useEffect(() => {
  const eventSource = new EventSource(API_URL);

  eventSource.onmessage = (event) => {
    if (event.data === "[DONE]") {
      eventSource.close();
      return;
    }

    const parsedData = JSON.parse(event.data);
    setDiagnoses(parsedData.D_list);
    setGenderDetails(parsedData.gender_details);

    containerRef.current?.scrollTo({
      top: containerRef.current.scrollHeight,
      behavior: "smooth",
    });
  };

  eventSource.onerror = () => {
    eventSource.close();
  };

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

Step 3: Render the Real-Time Data

We display the diagnoses and auto-scroll to the latest update in a styled container.

return (
  <div
    ref={containerRef}
    style={{
      maxHeight: "400px",
      minWidth: "800px",
      overflowY: "auto",
      border: "1px solid #ccc",
      borderRadius: "4px",
      padding: "1.5rem",
    }}
  >
    <h3>Gender: {genderDetails?.sex}</h3>
    {diagnoses?.map((diagnosis) => (
      <div key={diagnosis.id}>
        <h4>
          {diagnosis.diagnosis} ({diagnosis.probability}%)
        </h4>
        <p>{diagnosis.reason_for_diagnosis}</p>
        <p>
          <strong>Treatment Options:</strong> {diagnosis.treatment_options}
        </p>
        <h5>Suggestions:</h5>
        <ul>
          {diagnosis.suggestion_list?.map((suggestion) => (
            <li key={suggestion.id}>{suggestion.question}</li>
          ))}
        </ul>
      </div>
    ))}
  </div>
);

3. Key Features of the Code

  1. Auto-Scrolling: Automatically scrolls to the bottom of the container when new data arrives.

  2. Graceful Error Handling: Closes the connection on errors to prevent memory leaks.

  3. Real-Time UI Updates: The diagnoses and suggestions update seamlessly as new data streams in.


SSE vs WebSockets: Which to Choose?

FeatureSSEWebSockets
DirectionOne-way (server → client)Two-way (client ↔ server)
ProtocolHTTP/1.1Custom TCP connection
Ease of ImplementationEasierSlightly complex
ConnectionAuto-reconnect supportedManual reconnect required
Use CasesLive updates, dashboardsChats, gaming, collaborative apps

Why Choose SSE?

  1. Simple to Implement: No third-party libraries are required.

  2. Built-in Reliability: Automatically retries connections when interrupted.

  3. Lightweight: Ideal for streaming plain text updates.


What I Learned

  • SSE is a game-changer for real-time, one-way communication.

  • It’s perfect for scenarios where server → client updates dominate.

  • With proper state management and UI design, SSE makes real-time apps effortless to build.


Code Snippet for Quick Reference

useEffect(() => {
  const eventSource = new EventSource(API_URL);

  eventSource.onmessage = (event) => {
    const parsedData = JSON.parse(event.data);
    setDiagnoses(parsedData.D_list);
    setGenderDetails(parsedData.gender_details);

    containerRef.current?.scrollTo({
      top: containerRef.current.scrollHeight,
      behavior: "smooth",
    });
  };

  eventSource.onerror = () => eventSource.close();

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

Conclusion

SSE is a lightweight and powerful tool for building real-time applications in React. Whether it’s live notifications, dashboards, or data streams, SSE simplifies the development process while ensuring reliability.

If you’re looking to build a scalable, real-time React app, give SSE a try. Let me know your thoughts or questions in the comments below!

0
Subscribe to my newsletter

Read articles from Sandip Deb directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Sandip Deb
Sandip Deb

I specialize in React and the MERN stack, which includes MongoDB, Express, React, and Node. With years of experience in software development, I have honed my expertise in creating dynamic and responsive web applications using these technologies. I have a proven track record of developing top-quality web applications and managing projects from conception to launch. My technical proficiency, combined with my ability to work effectively in a team, enables me to create solutions that are scalable, secure, and high-performing. I am always learning and expanding my knowledge of new technologies and industry best practices.