Package Exports
- react-pusher-client
- react-pusher-client/dist/index.js
- react-pusher-client/dist/index.mjs
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (react-pusher-client) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
๐ก react-pusher-client
A lightweight React/Next.js wrapper for Pusher that simplifies client-side usage with hooks, connection state tracking, and auto-channel binding.
โจ Features
- โ Simple Pusher client initialization
- ๐ Track connection state with hooks
- ๐ง Auto-bind to channels/events
- ๐งช Works seamlessly in React or Next.js apps
- ๐งฉ Ideal for real-time dashboards, chat, notifications
- ๐ง Full control over Pusher client and custom hooks:
๐ฆ Installation
npm install react-pusher-client pusher-js
๐ Getting Started
- Initialize Pusher Client ๐
The first step is to initialize Pusher by providing your Pusher Key and optionally configuring the options (typically in a top-level component).
import { initPusher } from 'react-pusher-client';
// Initialize Pusher in your app
initPusher(process.env.NEXT_PUBLIC_PUSHER_KEY!, {
cluster: 'your-cluster',
});
- Using Hooks ๐
After initializing Pusher, you can use the provided hooks to interact with Pusher Channels, monitor connection states, and handle events.
API Reference ๐
initPusher(key: string, options?: Pusher.Options) ๐ง
Description: Initializes the Pusher client with the provided key and optional configuration. This function must be called once at the entry point of your app, before using any other hook.
Parameters:
key: The Pusher key obtained from your Pusher Dashboard.
options (optional): Additional configuration options for Pusher (e.g., cluster, encrypted).
Usage:
import { initPusher } from 'react-pusher-client';
// Initialize the Pusher client
initPusher('your-pusher-key', {
cluster: 'your-cluster',
});
usePusherEvent(channelName: string, eventName: string): T | null ๐
Description: A hook that listens for events on a specified Pusher channel and returns the event data.
Parameters:
channelName: The name of the channel to subscribe to.
eventName: The name of the event to listen for.
Returns:
The event data (T) received from Pusher, or null if no data is received.
Usage:
import { usePusherEvent } from 'react-pusher-client';
const message = usePusherEvent<{ user: string; message: string }>('chat', 'new-message');
return (
<div>
{message ? (
<p>
<strong>{message.user}:</strong> {message.message}
</p>
) : (
<p>Waiting for messages...</p>
)}
</div>
);
usePusherConnection(): string ๐
Description: A hook that tracks the Pusher connection state. The connection state can be one of the following:
connecting
connected
disconnected
reconnecting
failed
Returns:
The current connection state as a string.
Usage:
import { usePusherConnection } from 'react-pusher-client';
const connectionStatus = usePusherConnection();
return <p>Connection Status: {connectionStatus}</p>;
usePresenceChannel(channelName: string): PresenceMember[] ๐งโ๐คโ๐ง
Description: A hook that listens for updates on a Presence Channel and returns the list of online members. Presence channels are used to track users in real-time.
Parameters:
channelName: The name of the presence channel to subscribe to.
Returns:
An array of presence members. Each member has an id and other custom properties.
# Usage:
```typescript
import { usePresenceChannel } from 'react-pusher-client';
const onlineUsers = usePresenceChannel('chat');
return (
<div>
<h3>Online Users:</h3>
<ul>
{onlineUsers.map((user) => (
<li key={user.id}>{user.id}</li>
))}
</ul>
</div>
);
Custom Hook Example:
If you want full control over the Pusher client, you can directly access it via getPusher():
import { useEffect, useState } from 'react';
import { getPusher } from './lib/pusherClient';
const useCustomChannel = (channelName: string) => {
const [messages, setMessages] = useState<any[]>([]);
useEffect(() => {
const pusher = getPusher();
const channel = pusher!.subscribe(channelName);
const handleNewMessage = (message: any) => {
setMessages((prevMessages) => [...prevMessages, message]);
};
channel.bind('new-message', handleNewMessage);
return () => {
channel.unbind('new-message', handleNewMessage);
pusher!.unsubscribe(channelName);
};
}, [channelName]);
return messages;
};
Environment Variables ๐
You should set the following environment variables in your .env.local (or .env) file:
NEXT_PUBLIC_PUSHER_KEY=your-pusher-key
NEXT_PUBLIC_PUSHER_CLUSTER=your-cluster
This will make sure the Pusher key and cluster are accessible throughout your app, especially during development and production builds.
Best Practices ๐ก
- Single Initialization: Always call initPusher at the entry point of your app (e.g., in _app.tsx for Next.js apps) to ensure that the Pusher client is initialized only once.
- Efficient Event Listening: Use the usePusherEvent hook for event-based updates and the usePusherConnection hook to track connection status. Avoid subscribing to unnecessary channels or events to minimize unnecessary re-renders and optimize performance.
- Presence Channel Management: Use usePresenceChannel to track the state of users in real-time. Make sure to unsubscribe from channels when they are no longer needed to avoid memory leaks.
Troubleshooting โ ๏ธ
If you encounter any issues, please check the following:
Ensure that you have correctly set your Pusher key and cluster in your environment variables. Ensure that you are only calling initPusher once in your app. Verify that the channelName and eventName you are using are correct.
Contributing ๐ค
We welcome contributions to make pusher-react
better! If you have ideas, bugs, or features you'd like to add:
- Fork the repo
- Create your feature branch:
git checkout -b feat/your-feature
- Commit your changes:
git commit -m 'Add amazing feature'
- Push to the branch:
git push origin feat/your-feature
- Open a pull request โ
GitHub Repository: github.com/devnickjr/pusher-react
License ๐
This project is licensed under the MIT License - see the LICENSE file for details.