# Practical Stimulus: Building a Counter Component

*Published on August 23, 2023*

Tags: Hotwire

---


This is the third article in the&nbsp;[Practical Stimulus](/tag/hotwire)&nbsp;series, where we're learning various practical use-cases of&nbsp;[Stimulus.js](https://stimulus.hotwired.dev/)&nbsp;that you'd typically use either plain JavaScript or a single-page application framework like React or Vue.

In this post, we'll build a simple "counter" component to demonstrate&nbsp;**the basics of state management, event listening, and DOM targeting**, which are bread and butter tasks of front-end web development and the absolute core features of all JavaScript frameworks.

> If instead of Stimulus, you'd like to learn how to progressively build a counter using Turbo Drive, Turbo Frames and Turbo Streams, check out the following post: [Progressive Application Development with Hotwire](/progressive-application-development-with-hotwire)

## 

Start with HTML

Instead of JavaScript, HTML takes the center stage in Stimulus, by representing the state, classes, targets, and event handlers.

```html
<div data-controller="counter" data-counter-count-value="10">
  <div>
    <button data-action="click->counter#increment">Increment</button>
    <span data-counter-target="count">10</span>
  </div>
</div>
```

We'll learn what each attribute means later. To keep it clean, I've skipped the CSS classes on the HTML.

## Make it Dynamic with a Controller

Create a Stimulus controller named&nbsp;`counter_controller.js`.

💡 If you're using Rails, just run the&nbsp;`rails generate stimulus counter`&nbsp;command which will create one for you.

```javascript
// counter_controller.js

import { Controller } from "@hotwired/stimulus"

export default class extends Controller {
  static values = { count: Number }
  static targets = [ "count" ]

  increment() {
    this.countValue++
    this.countTarget.textContent = this.countValue
  }
}
```

That's it, we're done. The counter should be working as expected. Click on the button and watch the number getting incremented.

![counter.png](https://writesoftwarewell.com/media/jpovaf81wxnm8y7lxu2h10tiz3xa.png "Working Counter")

Let's walk through what's happening here.

## Declaring Data

Use the&nbsp;`data-{controller}-{name}-value`&nbsp;attribute to add state.

```html
<div data-controller="counter" data-counter-count-value="10">
```

Here, we connect our&nbsp;`<div>`&nbsp;to the&nbsp;`counter_controller.js`&nbsp;controller. We also define the initial count value to 10. You can access this data in the Stimulus controller using&nbsp;[Stimulus Values](https://stimulus.hotwired.dev/reference/values).

```javascript
export default class extends Controller {
  static values = { count: Number }

  connect() {
    console.log(this.countValue) // 10
  }
}
```

So that's how you manage state, by declaring it in the HTML markup and connecting it to the values on the controllers.

## Listening For Events

Use the&nbsp;`data-action`&nbsp;attribute to listen for any event on an element.

```html
<button data-action="click->counter#increment">Increment</button>
```

The attribute value follows the&nbsp;`event->controller#action`&nbsp;format. In this case, we want to listen for a&nbsp;`click`&nbsp;event on this button, and then call the&nbsp;`increment`&nbsp;method on the&nbsp;`counter`&nbsp;controller. So, we'll use&nbsp;`click->counter#increment`.

As you'd imagine, you can listen for other events. For example, listening for a&nbsp;`mouseenter`&nbsp;event would look like this:&nbsp;`mouseenter->counter#update`. To learn more, check out&nbsp;[Stimulus Actions](https://stimulus.hotwired.dev/reference/actions).

When a&nbsp;`click`&nbsp;event happens, Stimulus will call the associated controller method,. In this case, it's the&nbsp;`increment`&nbsp;method on counter controller. As you can see, we have direct access to the&nbsp;`countValue`&nbsp;property declared above.

```javascript
increment() {
    this.countValue++
}
```

On the action attribute, you'll often see&nbsp;`click`&nbsp;is skipped as Stimulus infers it by default. For clarity, I prefer to leave it there.

## Reacting to Changes

Use the&nbsp;`data-{controller}-target`&nbsp;attribute to mark the target of interest.

```html
<span data-counter-target="count"></span>
```

Here, we want to update the contents of this div, so we mark it with data target attribute.

You can access this div element in the controller using&nbsp;[Stimulus Targets](https://stimulus.hotwired.dev/reference/targets):

```javascript
export default class extends Controller {
  static values = { count: Number }
  static targets = [ "count" ]

  connect() {
    console.log(this.countTarget)
  }
}
```

The only thing remaining is to update the contents of this target when the user clicks the button.

```javascript
increment() {
  this.countValue++
  this.countTarget.textContent = this.countValue
}
```

And that's how you can build a simple counter component in Stimulus.

Although the resulting HTML might look intimidating, after working with Stimulus for almost two years I've come to realize that&nbsp;**it results in a highly readable, and as a result, maintainable code**. Reading the HTML practically tells you what's going on with a set of conventions and you rarely have to refer to the underlying JavaScript to understand the component.

