skip to content

A Stimulus character counter inserts its counter element and starts a setInterval in connect(); after Turbo visits and Back-button restores, counters duplicate and timers pile up. Why, and how do you fix it?

level: seniorimportance: should knowfreq 42%

answer

  1. initialize once, connect many times
  2. Turbo swaps the body: new instances
  3. the cache snapshot keeps inserted DOM
  4. clear what connect() started in disconnect()
  5. turbo:before-cache@document resets transient UI

basics

~20 s

Each Turbo visit or cache restore brings new elements and new controller instances; the cached snapshot already holds the counter connect() inserted, and old intervals were never cleared. Server-render the counter, keep connect() idempotent, clear timers in disconnect().

solid answer

~40 s

Stimulus calls `initialize()` once per controller instance and `connect()` every time that element with that identifier enters the document; `disconnect()` runs when it leaves. A Turbo Drive visit installs a new `<body>`, so the old controllers disconnect, and before leaving Turbo clones the current page into its snapshot cache, including the counter `connect()` inserted. On Back, Turbo shows that clone: new elements, new controller instances, and `connect()` inserts a second counter. Meanwhile each old instance's `setInterval` keeps running because nothing cleared it. The fix: render the counter in the ERB as a target so `connect()` only updates it, keep `connect()` idempotent, clear timers and observers in `disconnect()`, use `@window`/`@document` descriptors instead of manual global listeners, and reset transient UI on `turbo:before-cache`.

code

javascript · 23 lines
javascript
// app/javascript/controllers/character_counter_controller.js
import { Controller } from "@hotwired/stimulus"

export default class extends Controller {
  static targets = ["input", "count"]

  connect() {
    this.update()
    this.timer = setInterval(() => this.update(), 1000)
  }

  disconnect() {
    clearInterval(this.timer)
  }

  update() {
    this.countTarget.textContent = this.inputTarget.value.length
  }

  reset() {
    this.element.classList.remove("is-over-limit")
  }
}

go deeper

for a junior

Recall the order initialize, connect, disconnect and that connect can run many times for one controller.

for a middle

Explain how Turbo Drive's body swap and cache restore create new elements and therefore new controller instances, and what disconnect must clean up.

for a senior

Diagnose duplicated DOM and leaked timers from a Turbo cache restore, and enforce idempotent connect, paired cleanup and server-rendered structure in review.

for a principal

Set a team rule that controllers decorate server HTML and own no structure, so Drive visits, cache restores and morph refreshes all stay correct by construction.

## The lifecycle Stimulus guarantees Stimulus tracks pairs of **element and identifier**. For each pair it keeps one controller instance and calls: | callback | when | |---|---| | `initialize()` | once, when the instance is created | | `[name]TargetConnected(el)` | each time a target appears; on the controller's own connection these run before `connect()` | | `connect()` | each time the element with that identifier is in the document | | `disconnect()` | each time it leaves: removed, its `data-controller` edited, or the body replaced | If the **same** element is detached and re-attached, Stimulus reuses its instance and calls `connect()` again without `initialize()`. A **different** element, even an identical copy, gets a brand-new instance. Callbacks run asynchronously, in the microtask after the DOM change, because Stimulus learns about changes from a `MutationObserver`. ## What Turbo Drive does to that lifecycle Turbo Drive turns link clicks and form submissions into fetches and swaps the page's `<body>`. Three facts combine into the bug: 1. **Every visit installs new elements.** The old body leaves, so its controllers disconnect; the new body's elements get new instances, so `initialize()` and `connect()` run again. 2. **Turbo caches a snapshot before leaving.** It dispatches `turbo:before-cache` and stores a clone of the current page. Whatever `connect()` added to the DOM, such as an inserted `<span class="counter">`, is now part of that clone. 3. **Back and Forward show the clone.** Restoring it inserts new elements again, so `connect()` runs on markup that already contains a counter and inserts a second one. The timers are a separate leak. `setInterval` belongs to the window, not the element, so an interval started in `connect()` survives `disconnect()` unless the controller stops it. Every visit to the posting form starts another one, each calling into an instance whose elements are gone. ## Fixing the character counter - **Render the counter in the view.** Put `<span data-character-counter-target="count">0</span>` in the ERB. `connect()` then only writes a number into an existing target and has nothing to duplicate. - **Make `connect()` idempotent.** Anything it must still add, guard with `hasCountTarget` or a check for the inserted element, so a second run changes nothing. - **Pair every start with a stop.** Keep the interval id on the instance and clear it in `disconnect()`; do the same for observers and third-party widgets. - **Prefer descriptors for global events.** Stimulus unbinds `resize@window->character-counter#layout` when the controller disconnects, while a hand-written `window.addEventListener` in `connect()` stays attached. - **Reset transient UI before caching.** `turbo:before-cache@document->character-counter#reset` lets the controller close a tooltip or clear a "Copied!" badge before the snapshot is taken, so the preview does not show stale state. ## Morphing refreshes behave differently A Turbo 8 page refresh with `turbo-refresh-method` set to `morph` patches the existing DOM instead of swapping the body. Elements that match keep their identity, so as long as their `data-controller` value is unchanged their controllers **stay connected** and `connect()` does not run again. Anything the controller inserted that the server's HTML lacks can be removed by the morph, and nothing re-inserts it. That is one more reason for the rule interviewers are listening for: **the server renders the structure, the controller only decorates and updates it.** ## Diagnosing it in the browser 1. Set `application.debug = true` in `controllers/application.js`; Stimulus then logs every `initialize`, `connect` and `disconnect`, so a visit followed by Back shows a fresh initialize on the restored page. 2. Inspect the restored page's markup: a second counter element that the server never rendered proves `connect()` wrote into the snapshot. 3. Log from the interval callback: messages from instances whose element is no longer connected (`this.element.isConnected` is false) prove the timer outlived `disconnect()`. ## A checklist for any controller 1. Can `connect()` run twice on markup it already changed without visible effect? 2. Does `disconnect()` undo everything `connect()` started outside the element? 3. Does the page still look right when restored from Turbo's cache, or after a morph? 4. Is any state that must survive navigation written into the HTML rather than kept only in an instance variable?

  • When does initialize() run more than once for what looks like the same form?
    Whenever the element is a different node. A Turbo visit or a cache restore inserts new elements, even if the markup is identical, so Stimulus creates a new instance and runs `initialize()` again. Only detaching and re-attaching the very same node reuses the instance and skips `initialize()`.
  • After switching the page to morph refreshes, the counter disappears after a broadcast. Why?
    With morphing, the form element survives, so the controller stays connected and `connect()` does not run again. If the counter was inserted by JavaScript, the server's HTML lacks it and the morph removes it, and nothing puts it back. Rendering the counter in the view fixes it.
  • Why can't you rely on turbo:load to set up and tear down this behaviour?
    `turbo:load` fires after Drive visits, but not when a frame loads or a stream inserts markup, and it gives no teardown point. Stimulus connects and disconnects controllers for any DOM change, whatever caused it, so lifecycle work belongs in `connect()` and `disconnect()`.

  • A Stimulus controller instance lives for the whole browser session across Turbo visits
  • initialize() runs before every connect() call
  • Intervals started in connect() stop automatically when the element is removed
  • Turbo's cached snapshot is taken from the original server HTML, not the live page
  • A morph refresh disconnects and reconnects every controller on the page