Enable Dark Mode!
how-to-use-server-sent-events-sse-in-react.jpg
By: Alan Joy

How to Use Server-Sent Events (SSE) in React

Technical React

Modern web applications often require real-time updates. Examples include live notifications, stock price updates, monitoring dashboards, and activity feeds. While technologies like WebSockets provide full-duplex communication, many applications only need server-to-client updates. In such cases, Server-Sent Events (SSE) offer a simple and efficient solution.

What Are Server-Sent Events (SSE)?

Server-Sent Events (SSE) allow a server to push updates to the browser over HTTP. Unlike polling, where the client repeatedly asks the server for updates, SSE allows the server to send data automatically whenever new information is available. SSE uses a built-in browser API called EventSource. This creates a persistent HTTP connection between the client and server.

When Should You Use SSE?

SSE is ideal for applications that require real-time updates from the server but do not require client-to-server streaming.

Common Use Cases

  • Live notifications
  • Monitoring dashboards
  • Activity feeds
  • Live logs
  • Stock prices
  • Deployment status updates

How SSE Works

  1. The client creates an EventSource connection
  2. The server keeps the connection open
  3. When new data is available, the server pushes events
  4. The browser automatically receives the updates

Basic SSE Example in React

import { useEffect, useState } from "react";
export default function Notifications() {
  const [notifications, setNotifications] = useState([]);
  useEffect(() => {
    const eventSource = new EventSource("/api/notifications");
    eventSource.onmessage = (event) => {
      const data = JSON.parse(event.data);
      setNotifications((prev) => [...prev, data]);
    };
    eventSource.onerror = (error) => {
      console.error("SSE connection error:", error);
      eventSource.close();
    };
    return () => {
      eventSource.close();
    };
  }, []);
  return (
    <div>
      <h2>Notifications</h2>
      {notifications.map((item, index) => (
        <p key={index}>{item.message}</p>
      ))}
    </div>
  );
}

How This Works

  • EventSource opens a connection to /api/notifications
  • The server sends events
  • React updates state whenever new data arrives
  • Cleanup closes the connection when the component unmounts

Creating a Reusable SSE Hook

Custom Hook

import { useEffect, useRef } from "react";
export function useSSE(url, onMessage) {
  const eventSourceRef = useRef(null);
  useEffect(() => {
    const eventSource = new EventSource(url);
    eventSourceRef.current = eventSource;
    eventSource.onmessage = (event) => {
      const data = JSON.parse(event.data);
      onMessage(data);
    };
    eventSource.onerror = (error) => {
      console.error("SSE Error:", error);
      eventSource.close();
    };
    return () => {
      eventSource.close();
    };
  }, [url, onMessage]);
}

Using the Hook

import { useState } from "react";
import { useSSE } from "./useSSE";
export default function ActivityFeed() {
  const [activities, setActivities] = useState([]);
  useSSE("/api/activity", (data) => {
    setActivities((prev) => [...prev, data]);
  });
  return (
    <div>
      <h2>Activity Feed</h2>
      {activities.map((activity, index) => (
        <p key={index}>{activity.text}</p>
      ))}
    </div>
  );
}

Server-Sent Events provide a simple and efficient way to implement real-time updates in React applications. Key advantages include: simple HTTP-based implementation, built-in browser support, automatic reconnection, and lower complexity than WebSockets

For applications like notifications, monitoring dashboards, and activity feeds, SSE is often the best balance between simplicity and real-time performance.

To read more about What are the Key Features in React 19, refer to our blog What are the Key Features in React 19.


Frequently Asked Questions

What is the main advantage of SSE over polling?

SSE allows the server to push updates automatically, avoiding repeated requests from the client and improving efficiency.

Can SSE replace WebSockets?

SSE works well for one-way communication (server to client), but WebSockets are better when you need two-way, real-time interaction.

Does SSE automatically reconnect if the connection drops?

Yes, the browser automatically tries to reconnect to the server if the SSE connection is lost.

If you need any assistance in odoo, we are online, please chat with us.



0
Comments



Leave a comment



whatsapp_icon
location

Calicut

Cybrosys Technologies Pvt. Ltd.
Neospace, KINFRA Techno Park
Kakkanchery, Calicut
Kerala, India - 673635

location

Kochi

Cybrosys Technologies Pvt. Ltd.
1st Floor, Thapasya Building,
Infopark, Kakkanad,
Kochi, India - 682030.

location

Bangalore

Cybrosys Techno Solutions
The Estate, 8th Floor,
Dickenson Road,
Bangalore, India - 560042

Send Us A Message