Stimulus
HTML-centric lightweight JavaScript framework
Stimulus is Hotwire's JavaScript framework that declaratively connects JS behavior by adding attributes to HTML.
<div data-controller="hello">
<input data-hello-target="name" type="text">
<button data-action="click->hello#greet">Greet</button>
<span data-hello-target="output"></span>
</div>
// app/javascript/controllers/hello_controller.js
import { Controller } from "@hotwired/stimulus"
export default class extends Controller {
static targets = ["name", "output"]
greet() {
this.outputTarget.textContent =
`Hello, ${this.nameTarget.value}!`
}
}
3 core concepts:
Controller:
data-controller="name"โ connect JS controllerAction:
data-action="event->controller#method"โ eventโmethod mappingTarget:
data-controller-target="name"โ DOM element reference
Additionally: Values (data-controller-value-name), Classes (data-controller-class-name), Outlets (reference other controllers)
Key Points
Connect controller to HTML element with data-controller="name"
Define static targets = ["output"] โ reference DOM with data-name-target="output"
Connect event handler with data-action="click->name#method"
connect() โ auto-called when controller connects to DOM
disconnect() โ auto-called when removed from DOM (cleanup)
Pass data from HTML attributes with static values (data-name-url-value="...")
Pros
- ✓ HTML-centric โ naturally combines with server rendering
- ✓ Lightweight (very small compared to React/Vue)
- ✓ Perfectly compatible with Turbo
- ✓ Low learning curve
Cons
- ✗ Limited for complex client-side logic
- ✗ Difficult SPA-level state management
- ✗ Smaller community vs React/Vue ecosystem
- ✗ Inter-controller communication can be complex