DEV Community

Arhan Khan
Arhan Khan

Posted on

Stimulus for Beginners: Add JavaScript Sprinkles Without a Framework

Stimulus is a small JavaScript framework from the makers of Ruby on Rails, built for a simple idea: your HTML already describes your page, so your JavaScript should attach to it instead of taking it over. You do not build your UI in JavaScript. You write normal HTML, then connect small controllers to it.

A Stimulus controller is a class that connects to an element through a data-controller attribute. Inside the controller you declare targets (elements you need) and actions (events you respond to). That is almost the whole API.

Here is a working example — a button that toggles a hidden section:

<div data-controller="toggle">
  <button data-action="click->toggle#show">Show details</button>
  <p data-toggle-target="details" hidden>Here are the details.</p>
</div>
Enter fullscreen mode Exit fullscreen mode
import { Controller } from "@hotwired/stimulus";

export default class extends Controller {
  static targets = ["details"];

  show() {
    this.detailsTarget.hidden = false;
  }
}
Enter fullscreen mode Exit fullscreen mode

The HTML says what it is. The controller says what happens. No virtual DOM, no build step required for the basics, and no state living in JavaScript that can drift away from the page.

To start, add Stimulus with npm install @hotwired/stimulus, create an application, register your controllers, and add data-controller attributes to your HTML. It pairs naturally with server-rendered apps — Rails, Django, Laravel, or plain HTML pages.

Stimulus is a great fit if your app is mostly server-rendered and you only need interactivity in small doses: toggles, tabs, dropdowns, form enhancements, live search boxes. It keeps your JavaScript small, readable, and close to the HTML it controls.

The limits follow from the design. Stimulus is not for building a full single-page app — there is no routing or client-side state management. If your UI is mostly dynamic and lives in the browser, a bigger framework fits better.

Try it on one feature: take a dropdown or modal in a project you already have and rebuild it as a Stimulus controller. If the code ends up shorter and clearer, Stimulus is doing its job.

Top comments (0)