npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

react-use-sse-event

v0.2.2

Published

React hook for EventSource (SSE) with auto-reconnect, JSON parse, and subscribe API.

Readme

📡 react-use-sse-event

A lightweight React hook for Server-Sent Events (SSE) with automatic reconnection, JSON parsing, and a simple subscribe API.
Perfect for handling real-time data in React components.


✨ Features

  • 🔹 Manage SSE connections easily (EventSource)
  • 🔄 Automatic reconnection with exponential backoff
  • 🧩 Subscribe to multiple events with multiple listeners
  • 🔧 Automatic JSON parsing (stringobject)
  • 🍪 Supports cookies with withCredentials
  • 🧹 Automatic cleanup on component unmount
  • 📝 Option to limit stored messages (maxMessages)

📦 Installation

npm install react-use-sse-event
# or
yarn add react-use-sse-event

🚀 Basic Usage

import React, { useEffect } from "react";
import { useSSE } from "react-use-sse-event";

type BidType = {
  bidder: string;
  bidPrice: number;
  createDate: string;
};

export default function App() {
  const { connected, messages, subscribe } = useSSE<BidType>(
    "https://example.com/sse"
  );

  useEffect(() => {
    // Subscribe to a custom event "addBid"
    const unsubscribe = subscribe("addBid", (event) => {
      console.log("Bid:", event.data);
    });

    return () => unsubscribe();
  }, [subscribe]);

  return (
    <div>
      Connection status: {connected ? "Connected" : "Disconnected"}
      <div>
        Received bids:
        {messages.map((msg, idx) => (
          <pre key={idx}>
            Bidder: {msg.data.bidder}, Price: {msg.data.bidPrice}
          </pre>
        ))}
      </div>
    </div>
  );
}

⚙️ Advanced Usage (with options)

import { useSSE } from "react-use-sse-event";
import Cookies from "js-cookie";

const { connected, lastMessage, messages, subscribe, reconnect, close } =
  useSSE("https://example.com/sse", {
    withCredentials: true, // include cookies
    retryDelay: 1000, // initial reconnect delay (ms)
    maxRetryDelay: 30000, // maximum reconnect delay (ms)
    maxMessages: 100, // store only last 100 messages
    onOpen: () => console.log("SSE Connected!"),
    onError: (err) => console.error("SSE Error:", err),
    getHeaders: () => ({
      Authorization: `Bearer ${Cookies.get("Authorization")}`,
    }),
  });

🛠 Options

| Option | Type | Default | Description | | ----------------- | ------------------------------- | ----------- | -------------------------------------- | | withCredentials | boolean | false | Include cookies in requests | | retryDelay | number | 1000 | Initial reconnect delay (ms) | | maxRetryDelay | number | 30000 | Maximum reconnect delay (ms) | | maxMessages | number | Infinity | Maximum number of messages to keep | | onOpen | (ev: Event) => void | undefined | Callback when connection opens | | onError | (err: Event \| Error) => void | undefined | Callback on error | | getHeaders | () => Record<string, string> | undefined | Optional headers (e.g., Authorization) |

📡 API

const {
  connected, // boolean: connection status
  lastMessage, // last received message
  messages, // all messages (automatically accumulated)
  subscribe, // add listener for a specific event
  close, // manually close the connection
  reconnect, // manually reconnect
} = useSSE(url, options);

🔔 subscribe(eventName, callback)

  • Allows multiple components to listen to SSE messages.
  • Returns an unsubscribe function.
const unsubscribe = subscribe("addBid", (event) => {
  console.log(event.data);
});

unsubscribe(); // stop listening

🧼 Automatic Cleanup

  • The hook automatically closes the EventSource and clears timers on component unmount.
  • No need to worry about memory leaks.

🔧 JSON Parsing

The hook automatically parses incoming JSON strings:

// Server sends:
"{\"name\":\"hong gildong\"}";

// useSSE parses it automatically:
{
  name: "hong gildong";
}

📌 Summary

react-use-sse-event is perfect for:

  • Real-time dashboards

  • Live bidding apps

  • Chat apps

  • Notifications

  • Any use case requiring SSE in React