react-native-sse provides a robust, native-friendly `EventSource` implementation for React Native applications, enabling Server-Sent Events (SSE) on both iOS and Android platforms. The current stable version is 1.2.1, with a demonstrated active release cadence focused on features and fixes, as seen in recent minor updates. A key differentiator is its use of `XMLHttpRequest` internally, which eliminates the need for additional native module implementations, simplifying installation and integration. The library fully supports TypeScript, ensuring type safety for event listeners and configuration. It's commonly utilized for real-time data synchronization with systems like Mercure and is compatible with modern streaming APIs, including those used for AI interactions like ChatGPT. Its design prioritizes ease of use and broad compatibility within the React Native ecosystem.
npm install react-native-sseVerified import paths — ran on the pinned version, not inferred.
This example demonstrates how to establish an SSE connection, configure authentication with a Bearer token, listen for `open`, `message`, `error`, and `close` events, parse incoming JSON data, manage component state with real-time updates, and ensure proper connection cleanup in a React Native functional component.
To ensure listeners always access the current state or props, either wrap the listener function in `useCallback` with appropriate dependencies, use a mutable ref (e.g., `useRef`) to hold the latest state, or retrieve the current state directly from a global state management solution like Redux within the listener callback.
Include `import 'react-native-url-polyfill/auto';` once at the entry point of your application (e.g., `index.js` or `App.tsx`) or wherever `URL` objects are constructed for SSE connection URLs.
Upgrade to `react-native-sse` version `1.2.1` or newer to benefit from fixes ensuring correct `close` event dispatching and improved compatibility with various SSE server implementations (e.g., `sse-starlette`). Always ensure `es.close()` is explicitly called during component unmount or when the connection is no longer needed.
Verify the SSE server URL is correct and accessible. Ensure the server is running and configured to serve SSE (e.g., `Content-Type: text/event-stream` header) and that there are no cross-origin resource sharing (CORS) policies preventing your React Native app's domain from connecting.
Debug the SSE endpoint on the server side. Access the SSE URL directly in a web browser or using a tool like Postman to inspect the raw response. Ensure the server consistently sends `text/event-stream` with properly formatted SSE messages, ideally with JSON payloads if that is the expected data format.
To make the listener dynamic, use `useCallback` to memoize the listener and list all relevant state/props in its dependency array. Alternatively, if using a global state management system, access the current state directly from the store instance within the listener.