Server-Sent Events (SSE) are commonly used in real-time applications where the server needs to push updates to the client.
Here are a few use cases:
- Real-time notifications: SSE can be used to push notifications to the client in real-time. For example, in a social media application, the server can push notifications about new posts, likes, comments, etc.
- Live news updates: In a news application, the server can push live news updates to the client.
- Real-time analytics: In an analytics dashboard, the server can push real-time data updates to the client.
- Chat applications: In a chat application, the server can push new messages to the client in real-time.
- Online multiplayer games: In an online multiplayer game, the server can push game state updates to the client in real-time.
- Stock price updates: In a stock trading application, the server can push real-time stock price updates to the client.
useSse
is a custom React hook for handling Server-Sent Events (SSE) in your application.
Here's a basic example of how to use the useSse
hook:
import { useEffect } from 'react';
import useSse from './useSse';
const MyComponent = () => {
const {
connectionState,
connectionError,
addListener,
getEventData,
closeConnection,
} = useSse('https://my-api.com/events', { withCredentials: true });
// register the listener once, clean it up on unmount
useEffect(() => {
const remove = addListener('myEvent', data => {
console.log('Received data:', data);
});
return () => {
remove?.(); // detach the listener
closeConnection(); // close the SSE connection
};
}, [addListener, closeConnection]);
// grab the latest payload for this event on every render
const data = getEventData('myEvent');
return (
<div>
<p>Connection state: {connectionState}</p>
{connectionError && <p>Error: {connectionError.message}</p>}
{data && <p>Last payload: {data}</p>}
</div>
);
};
export default MyComponent;
The useSse
hook returns an object with these properties:
connectionState
: current state of the SSE connection (CONNECTING
,OPEN
,CLOSED
)connectionError
: anEvent
object describing the most recent connection error, ornull
if none occurredaddListener(eventName, handler)
: registers a listener for the specified event; the handler receives the event data string. The function returns a cleanup callback you can call (or return from auseEffect
) to remove the listener when neededgetEventData(eventName)
: returns the latest payload string for the given event name. Because it comes from React state, a component that reads this value will automatically re-render whenever the payload changescloseConnection()
: closes the underlyingEventSource
and updatesconnectionState
toCLOSED
This is awesome!
Note that
The useState and useEffect hooks are being called inside the getEventData callback function. This violates the Rules of Hooks, which state that hooks must be called at the top level of React functions, not inside loops, conditions, or nested functions.
So I a fix would be to create this util in its own hook with its own lexical scope 🤓