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 useSse from './useSse';
const MyComponent = () => {
const { connectionState, connectionError, addListener, getEventData, closeConnection } = useSse('https://my-api.com/events', {
withCredentials: true
});
// Add event listener
addListener('myEvent', (data) => {
console.log('Received data:', data);
});
// Get event data
const [data, setData] = getEventData('myEvent');
console.log('Event data:', data);
// Close connection
closeConnection();
return (
<div>
<p>Connection State: {connectionState}</p>
{connectionError && <p>Error: {connectionError.message}</p>}
</div>
);
};
The useSse
hook returns an object with the following properties:
connectionState
: The current state of the SSE connection. Possible values are 'CONNECTING', 'OPEN', and 'CLOSED'.connectionError
: Any error that occurred while connecting to the SSE server.addListener(eventName, eventHandler)
: A function to add an event listener for a specific event. TheeventHandler
function will be called with the data from the event.getEventData(eventName)
: A function to get the data for a specific event. It returns a state variable and a setter function, similar to howuseState
works. The state variable is initialized with the current event data, and it's updated whenever the event data changes. This makesgetEventData
reactive, as changes to the event data will cause components using this data to re-render.closeConnection()
: A function to close the SSE connection.