Introduction to ActionCable

Learn about immediate communication with ActionCable.

Background

In the last chapter, we learned how to communicate with the server using regular HTTP requests and receiving either HTML or JSON in response. One feature of our server interactions in both Stimulus and React is that we are simulating a real-time connection with the server by polling the server repeatedly.

Problems with polling

Polling this way has some potential drawbacks. That is, there’s some extra overhead to make all the HTTP calls locally and querying the server often can have negative performance implications.

WebSocket protocol

An alternative for client-server communications is to use the WebSocket protocol. The WebSocket protocol allows a client and a server to communicate over a single long-lived connection. A common analogy is that regular HTTP connections perform like walkie-talkies in that only one of the two parties can broadcast at a time. A WebSocket is like a phone, where both parties can talk at once. A WebSocket is effectively a stream in both directions, where both client and server can perform actions when new data is received.

ActionCable integration

Rails provides a library called ActionCable, which is a wrapper around WebSockets that makes it easy to use a WebSocket on both the client and the server end. Beyond that, Hotwire and Turbo provide utilities that allow us to combine ActionCable and Turbo Streams to provide ActionCable functionality without writing any new JavaScript.

In this chapter, we’re going to take a look at the Turbo Streams methods that allow us to send Turbo Stream data with ActionCable and then how to use ActionCable with Stimulus controllers. We’ll also adapt our React components to receive ActionCable messages. First, let’s get ActionCable set up.

Installing ActionCable

The ActionCable installation has already been done as part of our generic Rails setup. The Ruby gem is part of our Gemfile and the JavaScript package is already in our package.json file. @types/actioncable with yarn add @types/actioncable has already been installed here, which contains TypeScript definitions for ActionCable client-side code, allowing us to use TypeScript with ActionCable.

ActionCable has some configurations that we can see in the config/cable.yml file:

Get hands-on with 1000+ tech skills courses.