Introduction to ActionCable
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.
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.
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.
The ActionCable installation has already been done as part of our generic Rails setup. The Ruby gem is part of our
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