Development
-
May 4, 2021

How to build a SPA using Hotwire

In the past few years, there has been a consistent rise in Single Page Applications (SPA). A lot of today's web application tech stacks rely on JSON APIs in the backend, with a frontend app modifying the DOM in the web browser, to help create a fast and seamless experience for users.

When Ruby on Rails was created, it was developed to render pages on the server. So, to build a SPA with Ruby on Rails running on the backend, you have to render JSON payloads as a response, and let the frontend take care of the rest.

But, what if the frontend could update the DOM, sending HTML from the backend instead of JSON?

This is where Hotwire comes into the picture.

Hotwire is self-described as:

an alternative approach to building modern web applications without using much JavaScript by sending HTML instead of JSON over the wire. This makes for fast first-load pages, keeps template rendering on the server, and allows for a simpler, more productive development experience in any programming language, without sacrificing any of the speed or responsiveness associated with a traditional single-page application.

Hotwire was created to replace heavy load JS SPAs with good old HTML, to encourage developers to view the application as a set of frames that can be replaced or augmented by the HTML, sent from the server.

Taking that into consideration, using Hotwire means maintaining the Ruby on Rails way of programming, as it mostly uses the Ruby on Rails views and partials that you will need to write.

Hotwire Components

Hotwire consists of the following three components:

  • Turbo: this is the heart of Hotwire. It consists of a set of techniques for speeding up page changes and form submissions, dividing complex pages into components, and streaming partial page updates over WebSocket, without writing any JS code.
  • Stimulus: some of the interactivity may need some JS code to work as required, so, for those cases where custom code is required, Stimulus makes this work.
  • Strada: this component is used to allow mobile hybrid applications to talk to each other via HTML bridge attributes. At the time of writing, Strada hasn't been released yet.

How can you get started?

First off, ask yourself, do you think this fits your product? If so, do you want to try it out on an MVP, or would you just like to see how it works?

At Rootstrap we make your life a lot easier by putting Hotwire together with Tailwind, Device, ActiveAdmin, and a few more useful custom options.

So, feel free to clone our Ruby on Rails Hotwire Base and start hacking!

Also, don't forget to give us a ⭐ if you found this useful.