useSSE React Hook
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
-
TypeError: Cannot destructure property 'data' of 'undefined' as it is undefined.
cause Attempting to access `data.isError` or similar properties on the returned data object when errors are now returned separately.fixUpdate your code to destructure the error object explicitly: `const [data, error] = useSSE(...);` and check `error` for details. -
Argument of type '{ data: string; }' is not assignable to parameter of type '() => Promise<any>'.cause Passing an initial state object as the first argument to `useSSE` in versions 2.0.0 or higher.fixRemove the initial state object. `useSSE` no longer accepts it: `useSSE(() => fetchData(), []);` -
Argument of type 'string' is not assignable to parameter of type '() => Promise<any>'.
cause Passing the `key` string as the second argument to `useSSE` in versions 1.0.0 or higher.fixRemove the `key` parameter. The `useSSE` hook no longer requires it: `useSSE(() => fetchData(), []);`
Warnings
- breaking The `key` parameter for the `useSSE` hook was removed. Previously, it was the second argument. Calls to `useSSE` with a key will now fail or behave unexpectedly.
- breaking The `useSSE` hook no longer accepts an initial state object as its first argument. The initial data state is now always `null` by default.
- breaking Errors are now returned separately from the data as the second element in the tuple `[data, error]`. Previously, errors might have been embedded within the `data` object (e.g., `data.isError`).
- gotcha Version 3.0.0-beta.0 introduces React 18 support. While it should be mostly compatible, users upgrading to React 18 should test thoroughly for any subtle behavioral changes or deprecated APIs, especially if relying on specific React lifecycle behaviors.
- gotcha Security dependencies, including `lodash` and `elliptic`, have been updated across several versions (v2.0.1, v3.0.0-beta.0). While these are usually internal, it's a reminder to keep dependencies updated to avoid potential transitive vulnerabilities.
Install
-
npm install use-sse -
yarn add use-sse -
pnpm add use-sse
Imports
- useSSE
const useSSE = require('use-sse');import { useSSE } from 'use-sse'; - UseSSEHook
import type { UseSSEHook } from 'use-sse';
Quickstart
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;