Rails View Magic
π Rails View Magic: Next-Level Strategies for Blazing-Fast Frontends β¨
Managing views in Ruby on Rails can make or break your appβs performance and maintainability. Letβs dive into cutting-edge approaches for structuring views with React, Hotwire, and vanilla JS, plus unique optimization tricks you wonβt find in most tutorials!
π₯ Modern View Management Techniques
1. ERB + View Components (For Ultra-Clean Templates) π§©
Instead of bloated partials, use View Componentsβa structured way to encapsulate view logic.
# app/components/post_component.rb
class PostComponent < ViewComponent::Base
def initialize(post:)
@post = post
end
end
<!-- app/components/post_component.html.erb -->
<div class="post">
<h2><%= @post.title %></h2>
<p><%= truncate(@post.body, length: 100) %></p>
</div>
Why?
β
Testable (unlike partials)
β
Encapsulated logic (no messy helpers)
β
Faster rendering (benchmarked vs partials)
2. React + Inertia.js (Seamless SPA Experience) βοΈπ₯
Skip API boilerplate! Inertia.js lets you use React/Vue while keeping Rails controllers.
// resources/js/Pages/Posts/Show.jsx
export default function Show({ post }) {
return (
<div>
<h1>{post.title}</h1>
<p>{post.body}</p>
</div>
);
}
# app/controllers/posts_controller.rb
def show
render inertia: 'Posts/Show', props: { post: @post }
end
Unique Perks:
π No API layer (direct data passing)
β‘ Auto partial reloads (like Hotwire, but for React)
3. Hotwire (Turbo + Stimulus) + Morphing π
Turbo Streams are great, but morphing (via Turbo 8) prevents flickering on updates.
# app/controllers/posts_controller.rb
def update
@post.update!(post_params)
render turbo_stream: turbo_stream.morph(@post)
end
Why Morphing?
π Preserves DOM state (e.g., form inputs, scroll position)
π― Smoother than full replaces
4. Islands Architecture (Hybrid Server + Client) ποΈ
Only hydrate interactive partsβperfect for content sites with some JS.
<!-- app/views/posts/show.html.erb -->
<%= render PostComponent.new(post: @post) %>
<!-- Only this part is hydrated -->
<%= content_for :hydrate do %>
<div data-controller="comments">
<%= render @post.comments %>
</div>
<% end %>
Optimization Wins:
π Less JavaScript load
β‘ Faster TTI (Time to Interactive)
β‘ Rare but Powerful Optimization Tricks
1. Database-Powered HTML Caching (PG + Fragment Caching)
Store pre-rendered HTML in Postgres JSON columns for ultra-fast reads.
# app/models/post.rb
class Post < ApplicationRecord
store :cached_html, accessors: [:body_html], coder: JSON
after_save :update_cached_html
def update_cached_html
self.body_html = ApplicationController.render(
partial: "posts/post",
locals: { post: self }
)
end
end
Use Case:
- High-traffic blogs (avoid re-rendering the same content)
2. CSS/JS Critical Path Inlining
Extract above-the-fold CSS/JS and inline it in <head>
for faster FCP.
<%# app/views/layouts/application.html.erb %>
<style>
<%= Rails.application.assets["critical.css"].to_s.html_safe %>
</style>
<%= javascript_include_tag "critical", defer: true %>
Tools to automate this:
- Critical (npm)
- Lighthouse CI (track regressions)
3. Brotli + Edge Caching for Turbo Streams
Compress Turbo Streams responses with Brotli (smaller than gzip).
# Nginx config
location / {
brotli_static on;
brotli_types text/vnd.turbo-stream.html;
}
Bonus: Cache Turbo Streams at the CDN level (e.g., Fastly).
4. Lazy-Loaded Stimulus Controllers
Load Stimulus controllers only when needed (saves KBs).
// app/javascript/controllers/lazy_loader.js
import { Application } from "@hotwired/stimulus"
const app = Application.start()
export function registerController(name, module) {
import(`./${name}_controller.js`)
.then(module => app.register(name, module.default))
}
<div data-controller="lazy-loader" data-action="mouseenter->lazy-loader#loadComments">
<!-- Loads only on hover -->
</div>
π The Ultimate Checklist for Rails Views
- β Use View Components (not partials) for complex UI
- β Pick Hotwire for most apps, React/Inertia for SPAs
- β Morph DOM updates (Turbo 8) for smoother UX
- β Cache HTML in DB for high-read endpoints
- β Inline critical CSS/JS + lazy-load the rest
- β Compress Turbo Streams with Brotli
- β Adopt Islands Architecture for content-heavy sites
π Final Thought
Rails gives you optionsβchoose wisely based on interactivity needs. For most apps:
- Start with Hotwire
- Optimize with DB caching + Brotli
- Measure with Lighthouse
Whatβs your favorite Rails frontend stack? Drop a comment! π
© Lakhveer Singh Rajput - Blogs. All Rights Reserved.