npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

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

v3.0.2

Published

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

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

// 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

  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