@kesha-antonov/react-native-action-cable
v3.0.2
Published
Use Rails ActionCable channels with React Native for real-time WebSocket communication.
Maintainers
Readme
Support my work
cryptoc - my crypto portfolio app. Your coins on the home screen, lock screen and watch face. iPhone, iPad, Mac, Apple Watch, Android, Android tablet and Wear OS.
- Portfolio with average buy price and 24h / 180-day / all-time P&L
- Widgets in three sizes, refreshed in the background - most days you never open the app
- Price alerts on 5,000+ coins, delivered while the app is closed
- No account, no email, no exchange API keys, no ads. Your holdings never reach a server - they sync through your own iCloud or Google Drive
- Free for 3 holdings, and that is not a trial timer
Downloading it is what pays for the time that goes into these libraries.
✨ Features
- 🔌 WebSocket Connection - Automatic connection management with reconnection support
- 📡 Channel Subscriptions - Subscribe to multiple ActionCable channels
- 🔄 Auto-Reconnect - Automatically reconnects when connection is lost
- 🔐 Custom Headers - Support for authentication and dynamic headers
- 📱 React Native Ready - Works without
windowobject polyfills, on the New Architecture (pure JS, no native module) - 🛡️ Connection Reuse - Prevent duplicate connections during hot reloads
- ⚡ TypeScript - Full TypeScript support included
📖 Table of Contents
- ✨ Features
- 📖 Table of Contents
- 📦 Installation
- 🚀 Quick Start
- 📚 API Reference
- ⚙️ Advanced Usage
- 🧪 Testing
- 📂 Examples
- 🤝 Contributing
- 👏 Credits
- 📄 License
📦 Installation
Yarn
yarn add @kesha-antonov/react-native-action-cablenpm
npm install @kesha-antonov/react-native-action-cableThe unscoped react-native-action-cable
is an alias that re-exports this package in full and resolves to the latest
release in the same major line. Use whichever name you prefer - the scoped one
is the canonical package.
🚀 Quick Start
1. Create a consumer
import { ActionCable, Cable } from '@kesha-antonov/react-native-action-cable'
const actionCable = ActionCable.createConsumer('ws://localhost:3000/cable')
const cable = new Cable({})2. Subscribe to a channel
const channel = cable.setChannel(
'ChatChannel',
actionCable.subscriptions.create({
channel: 'ChatChannel',
roomId: 1
})
)
channel
.on('received', (data) => console.log('Received:', data))
.on('connected', () => console.log('Connected!'))
.on('disconnected', () => console.log('Disconnected'))3. Send messages
channel.perform('send_message', { text: 'Hello!' })4. Cleanup
channel.unsubscribe()📚 API Reference
ActionCable
| Method | Description |
|--------|-------------|
| createConsumer(url, headers?) | Create a new consumer and connect |
| getOrCreateConsumer(url, headers?) | Reuse existing consumer or create new one |
| disconnectConsumer(url) | Disconnect and remove consumer from cache |
| startDebugging() | Enable debug logging |
| stopDebugging() | Disable debug logging |
Consumer Instance
| Method | Description |
|--------|-------------|
| subscriptions.create(params) | Create a channel subscription |
| connection.isOpen() | Check if connected |
| connection.isActive() | Check if connected or connecting |
| disconnect() | Disconnect from server |
Cable
| Method | Description |
|--------|-------------|
| setChannel(name, subscription) | Register a channel |
| channel(name) | Get channel by name |
Channel
| Method | Description |
|--------|-------------|
| on(event, callback) | Subscribe to events: received, connected, disconnected, rejected, error |
| on('connected', cb) | cb({ reconnected }) - reconnected is true when the subscription came back after a dropped connection |
| on('disconnected', cb) | cb({ willAttemptReconnect, code, reason }) - reason is where React Native reports why the socket dropped |
| on('error', cb) | cb({ message, event }) - a readable message, with the original platform event attached |
| removeListener(event, callback) | Remove event listener |
| perform(action, data) | Send message to server |
| unsubscribe() | Unsubscribe from channel |
⚙️ Advanced Usage
// Static headers
const actionCable = ActionCable.createConsumer('ws://localhost:3000/cable', {
'Authorization': 'Bearer token123'
})
// Dynamic headers (re-evaluated on each connection)
const actionCable = ActionCable.createConsumer('ws://localhost:3000/cable', () => ({
'Authorization': `Bearer ${getAuthToken()}`
}))Use getOrCreateConsumer to prevent duplicate connections during hot reloads:
// ❌ Creates new connection every time
const actionCable = ActionCable.createConsumer('ws://localhost:3000/cable')
// ✅ Reuses existing connection
const actionCable = ActionCable.getOrCreateConsumer('ws://localhost:3000/cable')channel.on('error', ({ message, event }) => {
console.warn('Connection error:', message)
// Handle: no internet, wrong URL, server down, auth failure
// `event` is the original platform event, if you need it
})
// React Native reports *why* a socket dropped on the close event
channel.on('disconnected', ({ willAttemptReconnect, reason }) => {
console.log(reason, willAttemptReconnect ? '- retrying' : '- gave up')
})function useActionCable(channelName: string, params: Record<string, unknown>) {
const [connected, setConnected] = useState(false)
useEffect(() => {
const channel = cable.setChannel(
channelName,
actionCable.subscriptions.create({ channel: channelName, ...params })
)
channel
.on('connected', () => setConnected(true))
.on('disconnected', () => setConnected(false))
.on('received', handleReceived)
return () => {
channel.removeListener('received', handleReceived)
channel.unsubscribe()
delete cable.channels[channelName]
}
}, [channelName])
return { connected, channel: cable.channel(channelName) }
}subscriptions.create accepts an optional mixin of callbacks, exactly like Rails
ActionCable, which makes existing Rails channel code portable:
const channel = actionCable.subscriptions.create({ channel: 'ChatChannel', roomId: 1 }, {
connected ({ reconnected }) { console.log('Connected!', reconnected) },
disconnected ({ willAttemptReconnect }) { console.log('Disconnected', willAttemptReconnect) },
received (data) { console.log('Received:', data) },
speak (text: string) { this.perform('speak', { text }) },
})
channel.speak('Hello!')A mixin replaces the event emitter callbacks it defines - use either style, not both for the same event.
Messages with data.action attribute are emitted as separate events:
# Rails sends:
{ action: 'speak', text: 'hello!' }// React Native receives:
channel.on('speak', (data) => {
console.log(data.text) // 'hello!'
})🧪 Testing
Jest Mock
jest.mock('@kesha-antonov/react-native-action-cable', () => ({
ActionCable: {
createConsumer: jest.fn(() => ({
subscriptions: {
create: jest.fn(() => ({
on: jest.fn().mockReturnThis(),
removeListener: jest.fn().mockReturnThis(),
perform: jest.fn(),
unsubscribe: jest.fn(),
})),
},
connection: {
isActive: jest.fn(() => true),
isOpen: jest.fn(() => true),
},
disconnect: jest.fn(),
})),
},
Cable: jest.fn(() => ({
channels: {},
channel: jest.fn(),
setChannel: jest.fn(),
})),
}))See examples/testing for complete testing examples.
Testing this library
The library itself is covered by a Jest suite in __tests__, which
drives the real connection code against a WebSocket double that behaves like a
Rails ActionCable server:
yarn test # run the suite
yarn test:coverage # run it with a coverage report
yarn typecheck # type-check the library and the tests📂 Examples
| Example | Description | |---------|-------------| | Complete Chat App | Full Rails backend + React Native frontend | | Apollo GraphQL | ActionCable with GraphQL subscriptions | | Testing | Jest mocks and testing patterns |
🤝 Contributing
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
👥 Author
Maintained by Kesha Antonov
I also build cryptoc - a crypto portfolio app with home screen, lock screen and Watch widgets, no account and no exchange API keys.
👏 Credits
Based on action-cable-react. Code in lib/action_cable is adapted from Rails ActionCable, last synced with Rails main in August 2026.
Where it differs on purpose: React Native AppState drives reconnects instead of document.visibilitychange, the WebSocket implementation and request headers are injectable, subscriptions emit error events, incoming React Native Blobs are released, and urls are resolved without a document.
Please note that this project is maintained in free time. If you find it helpful, please consider becoming a sponsor.
