8
Hooks

useSseListener

A hook for handling Server-Sent Events (SSE) connections with built-in reconnection and event handling.

useSseListener

The useSseListener hook provides a reliable way to establish and manage Server-Sent Events (SSE) connections in React applications. It handles connection management, reconnection logic, and event parsing with support for multiple event types.

SSE Listener
CLOSED
https://api.example.com/sse

No events received yet. Connect to start receiving events.

This is a simulated SSE connection for demonstration purposes.

Installation

Install the useSseListener hook using:

npx axionjs-ui add hook use-sse-listener

File Structure

use-sse-listener.ts

Parameters

PropTypeDefault
options
SseOptions
Required

Return Value

PropTypeDefault
status
'IDLE' | 'CONNECTING' | 'OPEN' | 'CLOSED' | 'ERROR'
-
events
SseEvent[]
-
lastEvent
SseEvent | null
-
error
Error | null
-
connect
() => void
-
disconnect
() => void
-
retryCount
number
-

Examples

Real-time Notifications

Use SSE to implement a real-time notification system.

Notifications
Disconnected

Connect to receive notifications

Real-time Dashboard Updates

import { useSseListener } from "@/hooks/use-sse-listener";
 
function DashboardUpdates() {
  const { lastEvent, events, status } = useSseListener({
    url: "/api/dashboard/updates",
    events: ["sales", "visitors", "errors", "performance"],
  });
  
  // Track metrics by type
  const [metrics, setMetrics] = useState({
    sales: 0,
    visitors: 0,
    errors: 0,
    performance: 100,
  });
  
  // Update metrics when new events arrive
  useEffect(() => {
    if (lastEvent) {
      switch (lastEvent.type) {
        case "sales":
          setMetrics(prev => ({ ...prev, sales: lastEvent.data.value }));
          break;
        case "visitors":
          setMetrics(prev => ({ ...prev, visitors: lastEvent.data.count }));
          break;
        case "errors":
          setMetrics(prev => ({ ...prev, errors: lastEvent.data.count }));
          break;
        case "performance":
          setMetrics(prev => ({ ...prev, performance: lastEvent.data.score }));
          break;
      }
    }
  }, [lastEvent]);
  
  return (
    <div>
      <div>Connection Status: {status}</div>
      
      <div>
        <h2>Real-time Metrics</h2>
        <div>Sales: ${metrics.sales.toFixed(2)}</div>
        <div>Visitors: {metrics.visitors}</div>
        <div>Errors: {metrics.errors}</div>
        <div>Performance: {metrics.performance}%</div>
      </div>
      
      <div>
        <h3>Recent Updates</h3>
        <ul>
          {events.slice(-5).reverse().map((event, index) => (
            <li key={index}>
              {event.type}: {JSON.stringify(event.data)} 
              ({new Date(event.timestamp).toLocaleTimeString()})
            </li>
          ))}
        </ul>
      </div>
    </div>
  );
}

Use Cases

  • Real-time Dashboards: Display live updates of metrics and KPIs
  • Chat Applications: Receive new messages without polling
  • Notification Systems: Push notifications to users as events occur
  • Live Activity Feeds: Display social media or application activity in real-time
  • Stock or Cryptocurrency Trackers: Display live price updates
  • Collaborative Editing: Receive changes from other users
  • System Monitoring: Track server health and performance metrics

Browser Support and Fallbacks

The Server-Sent Events API is supported in most modern browsers, but there’s no support in IE. For broader compatibility:

import { useSseListener } from "@/hooks/use-sse-listener";
import { usePolling } from "@/hooks/use-polling"; // Fallback for unsupported browsers
 
function LiveDataComponent() {
  const isSSESupported = 'EventSource' in window;
  
  // Use SSE when supported
  const sseResult = useSseListener({
    url: "/api/live-data",
    autoConnect: isSSESupported,
  });
  
  // Use polling as fallback
  const pollingResult = usePolling({
    fetchFn: () => fetch("/api/live-data").then(res => res.json()),
    interval: 5000,
    autoStart: !isSSESupported,
  });
  
  // Combine results based on browser support
  const data = isSSESupported 
    ? sseResult.lastEvent?.data
    : pollingResult.data;
  
  return (
    <div>
      <div>Using: {isSSESupported ? 'Server-Sent Events' : 'Polling Fallback'}</div>
      <div>Data: {JSON.stringify(data)}</div>
    </div>
  );
}

Performance Considerations

  • Battery Impact: SSE maintains an open connection which can impact battery life on mobile devices
  • Connection Limits: Browsers typically limit the number of concurrent connections to a domain
  • Reconnection Strategy: Implement exponential backoff for reconnection attempts
  • Event Filtering: Consider filtering events on the server to reduce unnecessary network traffic

Best Practices

  • Include clear visual indicators of the connection status
  • Implement proper error handling and reconnection logic
  • Consider memory usage when storing event history
  • Provide fallback mechanisms for unsupported browsers
  • Implement server-side event throttling for high-frequency events
  • Use appropriate content types for SSE responses (text/event-stream)

On this page