In a Stimulus controller, when does a callback such as secondsValueChanged(value, previousValue) run, and what does it receive on its first call?
answer
- <name>ValueChanged naming
- first call comes before connect()
- then every attribute change, from anywhere
- first previousValue: the default or undefined
- async, after a MutationObserver record
basics
~20 ssecondsValueChanged runs once as the controller connects, before connect(), then after every change to data-countdown-seconds-value from any source. It gets the decoded new and previous values; the first previous value is the default, or undefined if the attribute is absent.
solid answer
~40 sStimulus calls `[name]ValueChanged(value, previousValue)` for every declared value that has one. When the controller connects, the value observer starts before `connect()` runs, so each callback fires once up front: with the attribute's decoded value and the default as `previousValue` if the attribute is present, or with the default and `undefined` if it is absent. After that it fires whenever the attribute's text changes, including assignments through `this.secondsValue =`, `setAttribute` from other code, or a morph refresh patching the element. Those later calls are asynchronous, delivered from a `MutationObserver` after the current code finishes, and writing the same text again fires nothing. This makes the callback the natural place to render: actions change the value, the callback updates the DOM.
code
javascript · 21 lines// app/javascript/controllers/countdown_controller.js
import { Controller } from "@hotwired/stimulus"
export default class extends Controller {
static targets = ["display"]
static values = { seconds: Number }
connect() { this.timer = setInterval(() => this.tick(), 1000) }
disconnect() { clearInterval(this.timer) }
tick() {
if (this.secondsValue > 0) this.secondsValue -= 1
}
secondsValueChanged(seconds) {
const m = Math.floor(seconds / 60)
const s = String(seconds % 60).padStart(2, "0")
this.displayTarget.textContent = `${m}:${s}`
if (seconds === 0 && this.timer) clearInterval(this.timer)
}
}go deeper
Recall the naming rule secondsValueChanged and that it receives the new and previous values.
Explain that the first call happens before connect(), what previousValue holds then, and that later calls follow any attribute change asynchronously.
Centralise rendering in change callbacks so server re-renders, morphs and local actions converge, and avoid self-triggering loops and connect() ordering bugs.
Treat data attributes plus change callbacks as the client state model, and decide what stays server-owned so the page never needs a client-side store.
## The callback contract For any value declared in `static values`, a controller may define a method named after it: `seconds` gets `secondsValueChanged`, `warnAt` gets `warnAtValueChanged`. Stimulus calls it with two arguments, the **decoded** current value and the **decoded** previous value, so a Number callback receives numbers, not attribute strings. ## When it fires 1. **Once at connection, before `connect()`.** On each connection Stimulus starts its observers (actions, values, targets, outlets) and only then calls `connect()`. Starting the value observer fires the callback for every declared value that has one. 2. **On every later change to the attribute's text.** The source of the change does not matter: the generated setter, `setAttribute` from other code, a browser devtools edit, or a Turbo 8 morph refresh that patches the attribute on an element it keeps. 3. **When the attribute is removed.** The callback receives the default as the new value and the old decoded value as `previousValue`. Writing the same string again fires nothing, because Stimulus compares the new attribute text with the last text it saw. ## What the first call receives | situation at connection | `value` | `previousValue` | |---|---|---| | attribute present, `data-countdown-seconds-value="1800"`, declared `seconds: Number` | `1800` | `0`, the Number default | | attribute absent, declared `seconds: Number` | `0` | `undefined` | | attribute absent, declared `{ type: Number, default: 1800 }` | `1800` | `undefined` | The asymmetry is worth remembering: `previousValue` is `undefined` only when the attribute was missing, so a guard such as `if (previousValue === undefined) return` does not reliably detect "first call". ## Asynchronous delivery Stimulus learns about attribute changes from a **MutationObserver**, so a callback triggered by `this.secondsValue = 1799` runs after the current method returns, not inside the setter. Code on the line after the assignment sees the new attribute through the getter, but the callback's side effects have not happened yet. ## Patterns and pitfalls - **Render from the callback.** Let `tick()` only decrement `this.secondsValue`, and let `secondsValueChanged(seconds)` format the clock, toggle the warning style and dispatch an expiry event. Any change, including one the server makes, then renders the same way. - **Do not depend on `connect()` state in the first call.** The callback runs before `connect()`, so a field such as `this.timer` set there is still `undefined`. Create the state in `initialize()`, or guard for it. Targets are already reachable, because their getters query the DOM directly. - **Do not chase your own tail.** Assigning a different value to `this.secondsValue` from inside `secondsValueChanged` schedules another callback; decrementing there turns one tick into a burst of callbacks that runs the clock to zero at once, or an endless loop for values with no floor. - **Expect a fresh controller after a replace.** A Turbo Stream `replace` swaps the element for a new one, so the new controller starts from scratch and its callbacks fire as at any first connection, rather than as a change on the old one. ## A timeline for one candidate's timer 1. The view renders `data-countdown-seconds-value="1800"`. 2. Stimulus constructs the controller and calls `initialize()`. 3. The value observer starts: `secondsValueChanged(1800, 0)` renders `30:00`. 4. `connect()` starts the interval. 5. One second later `tick()` assigns `1799`; after `tick()` returns, `secondsValueChanged(1799, 1800)` renders `29:59`. 6. The server pauses the attempt and a morph refresh writes `1500`: `secondsValueChanged(1500, 1799)` runs without any reconnection. 7. The candidate navigates away: `disconnect()` clears the interval, and no further callbacks run for this instance. ## Why interviewers ask about it The callback is Stimulus' small reactive core: the attribute is the state, and `[name]ValueChanged` is the subscription. Candidates who know when it fires use it to keep rendering in one place; candidates who do not tend to duplicate rendering in `connect()`, in every action and in Turbo event handlers, and then chase inconsistent screens.
- Why is this.timer undefined inside the first secondsValueChanged call?Stimulus starts the value observer before calling `connect()`, so the first callback runs while `connect()` has not yet set the field. Create such state in `initialize()`, which runs when the instance is constructed, or guard for its absence.
- A morph refresh changes data-countdown-seconds-value on the existing element. What runs?With morphing, Turbo keeps the element and patches its attributes, so the controller stays connected and `secondsValueChanged` fires with the new and old values. `connect()` does not run again, which is why rendering belongs in the callback.
- Does assigning the same number twice fire the callback twice?No. Stimulus compares the attribute's new text with the text it last recorded and only calls the callback when they differ, so a repeated identical assignment is silent.
- xValueChanged only fires after connect(), never during startup
- previousValue is always undefined on the first call
- The change callback runs synchronously inside the setter
- Changing the attribute from outside the controller does not trigger the callback
- Decrementing a value inside its own change callback is harmless