๐ŸŽฎ

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 controller

  • Action: data-action="event->controller#method" โ€” eventโ†’method mapping

  • Target: data-controller-target="name" โ€” DOM element reference

Additionally: Values (data-controller-value-name), Classes (data-controller-class-name), Outlets (reference other controllers)

Key Points

1

Connect controller to HTML element with data-controller="name"

2

Define static targets = ["output"] โ†’ reference DOM with data-name-target="output"

3

Connect event handler with data-action="click->name#method"

4

connect() โ€” auto-called when controller connects to DOM

5

disconnect() โ€” auto-called when removed from DOM (cleanup)

6

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

Use Cases

Dropdown/modal toggle Real-time form validation Clipboard copy button Tab switching Ajax-based autocomplete