---
name: better-stimulus
description: Apply Better Stimulus best practices for writing maintainable, reusable StimulusJS controllers following SOLID principles
title: better-stimulus
canonical_url: https://skilld.dev/gh/obie/skills/better-stimulus
last_updated: 2026-09-24T22:23:19.000Z
---

> Index of every page on this site: [llms.txt](https://skilld.dev/llms.txt)

> **Skill from skilld.dev.** Follow the user's requested action.
> If the user asked to fork this Skill, follow the fork workflow below. Do not execute the Skill instructions while copying it.
> Otherwise, follow the instructions below for this session. You do not need to install anything.
>
> Supporting files, fetch one when the Skill refers to it: [references/architecture.md](https://skilld.dev/api/skills-raw/obie/skills/better-stimulus/references/architecture.md), [references/dom-and-turbo.md](https://skilld.dev/api/skills-raw/obie/skills/better-stimulus/references/dom-and-turbo.md), [references/error-handling.md](https://skilld.dev/api/skills-raw/obie/skills/better-stimulus/references/error-handling.md), [references/events-and-interaction.md](https://skilld.dev/api/skills-raw/obie/skills/better-stimulus/references/events-and-interaction.md), [references/lifecycle.md](https://skilld.dev/api/skills-raw/obie/skills/better-stimulus/references/lifecycle.md), [references/solid-principles.md](https://skilld.dev/api/skills-raw/obie/skills/better-stimulus/references/solid-principles.md), [references/state-management.md](https://skilld.dev/api/skills-raw/obie/skills/better-stimulus/references/state-management.md).
>
> If the user asked to install this Skill, run `npx skilld install obie/skills/better-stimulus`. Install writes the Skill files into the project, so every session loads them.
>
> ## Fork workflow
>
> A fork creates an editable local Skill with its original author and licence. The request authorizes copying and local installation.
> 1. Check `./skills/better-stimulus`, the project lockfile, and selected Agent targets together. If the local directory or installed Skill exists, stop. Never overwrite an existing directory or Agent target.
> 2. Read [source metadata](https://skilld.dev/api/v1/skills/obie/skills/better-stimulus) once. Use sourceUrl, sourceCommit, skillPath, sourceGone, and license. If the source is gone or its path is missing, stop. If license is null, read licence files at the source commit.
> 3. Fetch only the source commit into a temporary Git repository. Do not clone full history. Derive repository_url from sourceUrl, including repository renames. If sourceCommit is absent, resolve the sourceUrl ref once. Set source_commit to that actual commit. Run these commands in one shell call:
>
> ```sh
> git init --quiet "$temporary_dir"
> git -C "$temporary_dir" fetch --quiet --depth=1 "$repository_url" "$source_commit"
> git -C "$temporary_dir" checkout --quiet --detach FETCH_HEAD
> ```
>
> Read applicable licence declarations and notices at that commit. If copying is not permitted, report the restriction and stop.
> 4. Inspect source entries together, then copy the directory containing skillPath into `./skills/better-stimulus`. Use the user's path if selected. Keep the original SKILL.md, relative links, scripts, binary assets, and executable modes. Exclude .git metadata. Reject symlinks and paths outside the Skill directory. After checking entries, use cp -a where available. A regular source directory needs no custom copy script. Do not save this page wrapper as SKILL.md.
> Preserve author credit, notices, and applicable licence files from repository or parent directories. Add PROVENANCE.md with the Skill page, source URL, actual commit, original path, and licence. Retain any existing PROVENANCE.md and record new provenance separately. Batch source inspection, copying, and provenance work where practical.
> 5. In the project root, run `skilld install ./skills/better-stimulus --mode copy --plain`. If skilld is unavailable, use `npx skilld install ./skills/better-stimulus --mode copy --plain`. This known command needs no help lookup. Install does not support --json. Use detected Agent targets, or add --agent for the targets the user selected. Install the local path, never the upstream selector. If installation fails, preserve the local copy and report the exact failure.
> 6. Confirm the local lockfile source and installed Agent copies once. Report the local path, actual commit, and Agent targets. After edits, reinstall the same local path. Upstream updates must not replace it. Do not publish or push unless the user asks.

# Better Stimulus

Apply opinionated best practices from [betterstimulus.com](https://betterstimulus.com/) when writing or refactoring Stimulus controllers. These patterns emphasize code reusability, proper separation of concerns, and SOLID design principles.

## When to Use This Skill

Invoke this skill when:
- Writing new Stimulus controllers
- Refactoring existing Stimulus code
- Reviewing Stimulus controller architecture
- Debugging inter-controller communication
- Integrating third-party JavaScript libraries
- Implementing form submission logic
- Managing controller state
- Setting up Turbo integration

## Core Principles

### 1. Make Controllers Configurable

**Externalize hardcoded values into data attributes** rather than embedding them in controller logic.

Bad:
```javascript
toggle() {
  this.element.classList.toggle("active")
}
```

Good:
```javascript
static classes = ["active"]
toggle() {
  this.element.classList.toggle(this.activeClass)
}
```
```html
<div data-controller="toggle" data-toggle-active-class="active"></div>
```

### 2. Use Values API for State

**Store controller state in Stimulus values**, not instance properties, to leverage reactivity and DOM persistence.

Bad:
```javascript
connect() {
  this.count = 0
}
```

Good:
```javascript
static values = { count: Number }
countValueChanged(count) {
  this.updateDisplay()
}
```

### 3. Keep Controllers Focused (Single Responsibility)

**Each controller should have one reason to change.** Split controllers that mix concerns.

Ask: "What would cause this controller to change?" If multiple unrelated reasons, split it.

### 4. Don't Overuse connect()

Use `connect()` for:
- Instantiating third-party plugins (Swiper, Chart.js, etc.)
- Feature detection/browser capabilities

Don't use `connect()` for:
- Setting up state (use Values API)
- Adding event listeners (use `data-action`)

### 5. Register Events Declaratively

**Use `data-action` attributes** instead of `addEventListener()` to let Stimulus manage lifecycle.

Bad:
```javascript
connect() {
  document.addEventListener("click", this.handler.bind(this))
}
```

Good:
```html
<div data-action="click@document->controller#handler"></div>
```

## Key Patterns

### Architecture

- **Configurable Controllers**: Inject dependencies via data attributes
- **Application Controller**: Base class for shared functionality
- **Mixins**: Share behavior via "acts as" relationships
- **Targetless Controllers**: Separate element vs. target manipulation
- **Namespaced Attributes**: Handle arbitrary parameter sets

See: `references/architecture.md`

### State Management

- Use Values API for nearly all state
- Leverage change callbacks (`[name]ValueChanged`)
- Keep values serializable
- Provide sensible defaults

See: `references/state-management.md`

### Lifecycle

- Use `connect()` for third-party library initialization
- Pair `connect()` with `disconnect()` for cleanup
- Avoid overloading `connect()` with state setup
- Implement `teardown()` for Turbo-specific cleanup

See: `references/lifecycle.md`

### Controller Communication

Three approaches:

1. **Custom Events**: Loose coupling, broadcast pattern
2. **Outlets**: Direct controller references, structured layouts
3. **Callbacks**: Request state from other controllers

Choose based on relationship:
- Unknown receivers → Custom events
- Known hierarchy → Outlets
- Data sharing → Callbacks

See: `references/events-and-interaction.md`

### SOLID Principles

- **Single Responsibility**: One reason to change
- **Open-Closed**: Extend via inheritance, not modification
- **Dependency Inversion**: Depend on abstractions, inject via config

See: `references/solid-principles.md`

### DOM & Turbo

- Use `<template>` to restore DOM state
- Use `requestSubmit()` not `submit()` for forms
- Implement global teardown for Turbo caching
- Handle Turbo events declaratively

See: `references/dom-and-turbo.md`

### Error Handling

- Create ApplicationController with `handleError()` method
- Integrate with error tracking (Sentry, Honeybadger)
- Provide user-friendly messages
- Use try-catch for async operations

See: `references/error-handling.md`

## Quick Reference

### Value Types
```javascript
static values = {
  url: String,
  count: Number,
  enabled: Boolean,
  items: Array,
  config: Object
}
```

### Event Actions
```html
<!-- Element events -->
<div data-action="click->controller#method">

<!-- Global events -->
<div data-action="resize@window->controller#layout">
<div data-action="keydown@document->controller#handleKey">

<!-- Multiple actions -->
<div data-action="click->ctrl1#method1 click->ctrl2#method2">
```

### Custom Events
```javascript
// Dispatch
const event = new CustomEvent('name:action', {
  bubbles: true,
  detail: { key: 'value' }
})
this.element.dispatchEvent(event)

// Listen
data-action="name:action->controller#handler"
```

### Outlets
```html
<div data-controller="parent"
     data-parent-child-outlet=".child">
  <div class="child" data-controller="child"></div>
</div>
```

```javascript
static outlets = ['child']
this.childOutlets.forEach(outlet => outlet.method())
```

### Lifecycle Hooks
```javascript
connect()           // Element connected to DOM
disconnect()        // Element removed from DOM
[name]TargetConnected(element)      // Target added
[name]TargetDisconnected(element)   // Target removed
[name]ValueChanged(value, oldValue) // Value changed
[name]OutletConnected(outlet)       // Outlet connected
[name]OutletDisconnected(outlet)    // Outlet disconnected
```

## Implementation Workflow

When writing a new controller:

1. **Identify responsibility** - What single purpose does this serve?
2. **Choose state approach** - Use Values API unless non-serializable
3. **Declare static properties** - values, targets, classes, outlets
4. **Implement change callbacks** - React to value changes
5. **Keep connect() minimal** - Only for third-party setup
6. **Use declarative actions** - Avoid addEventListener
7. **Handle errors gracefully** - Wrap risky operations in try-catch
8. **Test lifecycle** - Verify connect/disconnect behavior

When refactoring:

1. **Check Single Responsibility** - Split if multiple concerns
2. **Extract configuration** - Move hardcoded values to data attributes
3. **Convert to Values API** - Replace instance properties with values
4. **Simplify connect()** - Move state and listeners out
5. **Use inheritance/mixins** - Share common behavior properly
6. **Decouple controllers** - Use events/outlets for communication
7. **Add error handling** - Implement handleError from ApplicationController

## Common Mistakes to Avoid

- ❌ Hardcoding CSS classes, selectors, or IDs in controllers
- ❌ Using instance properties for state instead of values
- ❌ Overloading `connect()` with state setup and event listeners
- ❌ Creating "page controllers" that handle multiple concerns
- ❌ Using `addEventListener()` without proper cleanup
- ❌ Calling `.bind()` separately in connect and disconnect
- ❌ Using `submit()` instead of `requestSubmit()`
- ❌ Modifying base classes instead of extending them
- ❌ Tight coupling between controllers
- ❌ Swallowing errors without logging or reporting

## Resources

All patterns in this skill come from [betterstimulus.com](https://betterstimulus.com/), an opinionated collection of StimulusJS best practices.

For detailed explanations and examples, see:
- `references/architecture.md` - Controller design patterns
- `references/state-management.md` - Values API usage
- `references/lifecycle.md` - Lifecycle best practices
- `references/events-and-interaction.md` - Communication patterns
- `references/solid-principles.md` - SOLID design principles
- `references/dom-and-turbo.md` - DOM manipulation and Turbo
- `references/error-handling.md` - Error management
