useSSE React Hook

2.0.1 · active · verified Tue Apr 21

useSSE is a React hook designed to facilitate Server-Side Rendering (SSR) by allowing data to be fetched on the server and then rehydrated on the client without an additional network request. This approach optimizes the initial page load performance of React applications by ensuring the first render already includes necessary data. The current stable version is 2.0.1, with an active beta branch (3.0.0-beta.0) introducing support for React 18. The library has seen periodic updates, including security fixes and adjustments to its API for improved usability and error handling. Its primary differentiator is simplifying the integration of server-side data fetching into React components, avoiding the common pitfall of client-side re-fetches for initial render data.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use the `useSSE` hook to fetch data asynchronously, suitable for SSR scenarios. It shows how to pass a data-fetching function and a dependency array, and how to handle loading and error states.

import React from 'react';
import { useSSE } from 'use-sse';

// This function simulates an asynchronous data fetch that would typically happen on the server.
// In a real SSR setup, the return value would be serialized into the HTML and picked up by useSSE.
async function fetchData(itemId: string) {
  return new Promise<{ id: string; name: string }>(resolve => {
    setTimeout(() => {
      resolve({ id: itemId, name: `Item Data for ${itemId}` });
    }, 100); // Simulate network latency
  });
}

interface MyComponentProps {
  initialItemId: string;
}

function MyComponent({ initialItemId }: MyComponentProps) {
  // useSSE takes a data fetching function and a dependency array.
  // If running on the server, it executes `fetchData` and serializes the result.
  // On the client, it checks for serialized data before potentially re-running `fetchData`.
  const [data, error] = useSSE(() => fetchData(initialItemId), [initialItemId]);

  if (error) {
    return <div style={{ color: 'red' }}>Error loading data: {error.message}</div>;
  }

  if (!data) {
    // This will typically show on the client while hydrating if data isn't immediately available
    // or during initial client-side rendering if no SSR occurred.
    return <div>Loading...</div>;
  }

  return (
    <div>
      <h1>useSSE Example</h1>
      <p>Data loaded:</p>
      <pre>{JSON.stringify(data, null, 2)}</pre>
      <p>This data was likely pre-fetched during server-side rendering, reducing client-side load time.</p>
    </div>
  );
}

// Example usage within a React application
const App = () => <MyComponent initialItemId="product-abc" />;

export default App;

view raw JSON →