Introduction to Hotwire and Turbo
The Hotwire way
Hotwire is the generic name for the client-side toolkit written by the Basecamp team to power the Hey email application. The goal of Hotwire is to support an application in which most of its dynamic nature happens by making typical HTTP requests to the server, receiving HTML for a part of the page, and inserting that HTML in the correct place in the DOM for a page update.
The name “Hotwire” is derived from the phrase “HTML over the wire.”
The big picture:
The server communicates with the client by sending rendered HTML, not raw data. This HTML response may contain some metadata about where to put it when it arrives.
Any business logic the application might need should be on the server, not on the client.
Specific client logic should be limited only to interface items that the server won’t care about.
Where possible, client logic should be handled through the addition and removal of CSS classes. Doing so allows for a lot of client logic to be written generically.
The Hotwire team claims that about 80 percent of their client interaction is manageable via HTML over the wire, and at least half of the client-side code is just manipulating CSS. Applying this ratio to our application too will result in much less client-side complexity, and we’ll be able to leverage Rails features to keep the overall complexity low. Hotwire works particularly well if we use Rails conventions for partial-view files and especially if we use the ActiveRecord naming convention for partial files.
Turbo is the successor to Turbolinks. Its purpose is to make it easier to direct user actions into server requests. These requests then return partial HTML, which Turbo then inserts into the page or part of the page.
Hotwire and the asset pipeline
hotwire-railsgem. If Webpacker is not installed, the gem installs Turbo and Stimulus using the asset pipeline, including the Stimulus auto-load behavior we’ll talk about later. There’s also a gem called
tailwindcss-railsthat will do a default Tailwind installation in the asset pipeline or Webpacker. For a simple app, this is a low-overhead way to go.
To install Hotwire, we use a gem called
hotwire-rails, which is aware of whether we are using Webpacker or not and adjusts its installation accordingly.
- In the
Gemfile, replace the
rails hotwire:install. This will use npm and Webpacker to install Hotwire (both Stimulus and Turbo).
hotwire:install command does the following:
yarnto install the new package.
Makes a configuration change to ActionCable that we’ll talk about in Immediate Communication with ActionCable.
application.jsfile to remove Turbolinks, add the
turbo-railsgem, and import the
controllersdirectory that Stimulus uses. The following is an edited version; the installer puts the
import controllersat the end of the file: