Skip to content
 
 

Repository files navigation

CI npm version npm downloads total npm downloads npm downloads (last 18 months) used by dependent repos on libraries.io license platforms TypeScript

React Native ActionCable

Use Rails ActionCable channels with React Native for real-time WebSocket communication.

📖 Documentation  ·  Installation  ·  Quick start  ·  API reference  ·  Advanced usage

Using it in production? A ⭐ helps other developers find the library.


cryptoc app icon

QR code that installs cryptoc
Scan to install

Download on the App Store
Get it on Google Play

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 window object 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


📦 Installation

Yarn

yarn add @kesha-antonov/react-native-action-cable

npm

npm install @kesha-antonov/react-native-action-cable

The 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

Custom Headers & Authentication
// 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()}`
}))
Preventing Duplicate Connections

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')
Error Handling
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')
})
React Hook Example
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) }
}
Rails style channel mixins

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.

Custom Action Events

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

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. 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.


📄 License

MIT

Releases

Sponsor this project

Packages

Used by

Contributors

Languages