skip to content

Hotwire

Hotwire builds interactive pages by sending HTML over the wire: Turbo swaps pages, frames and streamed fragments, and Stimulus adds small controllers. Interviewers weigh it against a full SPA.

on this pageshow

explore

questions

page 1 of 2

In Stimulus, how do the data-controller, data-action and data-<identifier>-target attributes connect server-rendered HTML to a controller class?

level: juniorimportance: must knowfreq 72%

answer

  1. three attributes, one controller class
  2. file name becomes the identifier
  3. event->identifier#method
  4. static targets gives three properties
  5. singular target throws when missing

basics

~10 s

data-controller names an identifier, so Stimulus attaches that controller class to the element; data-action routes a DOM event to a controller method; data-<identifier>-target names elements the controller reads through generated properties such as this.sourceTarget.

solid answer

~40 s

Stimulus watches the document for `data-controller` attributes. Each space-separated identifier in one, such as `copy-link`, gets an instance of the controller class registered under that name; in a Rails app the name comes from the file, so `copy_link_controller.js` becomes `copy-link`. `data-action="click->copy-link#copy"` installs a listener that calls `copy(event)` on that instance. Elements marked `data-copy-link-target="source"` become reachable once the class declares `static targets = ["source"]`: Stimulus generates `this.sourceTarget` (the first match, throwing if there is none), `this.sourceTargets` (all matches) and `this.hasSourceTarget`. Everything is scoped to the controller's element and its descendants, and the state lives in the HTML the server rendered rather than in a client-side template.

code

html · 6 lines
html
<div data-controller="copy-link">
  <input type="text" readonly
         value="https://jobs.example.com/postings/42"
         data-copy-link-target="source">
  <button type="button" data-action="copy-link#copy">Copy link</button>
</div>

go deeper

for a junior

Recall the three attributes, the arrow syntax of an action, and how a file name like copy_link_controller.js becomes the identifier copy-link.

for a middle

Explain the three generated target properties, which one throws, and how scope excludes elements inside a nested controller with the same identifier.

for a senior

Show why keeping state in server-rendered HTML lets controllers survive Turbo body swaps, cache restores and morphs, and spot the deprecated data-target form in old views.

for a principal

Frame Stimulus as decoration of server HTML rather than a rendering layer, and judge when a screen's state has outgrown attributes and targets.

## Three attributes, one contract **Stimulus** is the JavaScript half of Hotwire. It does not render HTML. The server (in a Rails app, an ERB view) renders ordinary markup, and Stimulus attaches small **controllers** to it through three attribute families: - **`data-controller`** names which controller classes own an element; - **`data-action`** routes DOM events to methods on those controllers; - **`data-<identifier>-target`** names the elements a controller needs to read or change. Because the contract lives in attributes, the same controller keeps working when Turbo replaces the page body, loads a frame or applies a stream: Stimulus observes the document with a `MutationObserver` and connects whatever appears. ## Identifiers: the name in the HTML An **identifier** is the string inside `data-controller`. In a Rails app it is derived from the file path under `app/javascript/controllers/`: | controller file | identifier | |---|---| | `copy_link_controller.js` | `copy-link` | | `character_counter_controller.js` | `character-counter` | | `job_postings/copy_link_controller.js` | `job-postings--copy-link` | Underscores become dashes, a subdirectory becomes a double dash, and the `_controller` suffix is dropped. The exported class name plays no part; outside the Rails loaders you call `application.register("copy-link", CopyLinkController)` yourself. One element can carry several identifiers, as in `data-controller="copy-link character-counter"`, and each gets its own instance. ## Actions: events to methods `data-action="click->copy-link#copy"` is an **action descriptor**: the event name, the identifier and the method name. When the event fires, Stimulus calls `copy(event)` on the instance whose identifier matches. The descriptor has more syntax (default events, key filters, global targets, options, parameters), but the core is that one arrow. The action must sit on the controller's element or inside it: a descriptor naming a controller that is not on an ancestor never fires. ## Targets: named elements A controller lists its target names in a static array, and Stimulus generates three properties per name: | property | returns | |---|---| | `this.sourceTarget` | the first matching element in scope; **throws** `Missing target element "source" for "copy-link" controller` if there is none | | `this.sourceTargets` | an array of every match, possibly empty | | `this.hasSourceTarget` | a boolean, for optional targets | The attribute is `data-copy-link-target="source"`, and its value is a space-separated list, so one element can be several targets, or targets of several controllers at once. ## Scope: what a controller can see A controller's **scope** is its own element plus its descendants, minus anything inside a nested element carrying the **same** identifier. Two copy-link widgets on one job listing therefore never see each other's `source` targets, even when one sits inside the other. Targets elsewhere on the page are invisible; reaching another controller goes through outlets or events, which are a separate topic. ## Keeping state in the HTML The design point interviewers probe is where state lives. A Stimulus controller reads what it needs from the DOM (a target's value, an attribute) and writes its results back into the DOM (text, classes, attributes). Nothing is rendered from a JavaScript template, and nothing important lives only in a JavaScript variable, so a server re-render, a Turbo cache restore or a morph leaves the page consistent. A copy-link button on a job posting shows the whole contract: 1. The view renders a read-only input holding the posting URL with `data-copy-link-target="source"`. 2. The wrapper carries `data-controller="copy-link"`. 3. The button carries `data-action="copy-link#copy"` (a button's default event is `click`). 4. `copy()` reads `this.sourceTarget.value` and writes it to the clipboard. ## Mistakes that fail quietly Several wiring errors produce no exception at all, which is why they come up in interviews: - **An identifier typo** (`data-controller="copylink"`) matches no registered controller, so nothing connects and nothing is logged. - **A target name missing from `static targets`** generates no property: `this.sourceTarget` is plain `undefined`, and the error you see is a `TypeError` on the next line rather than Stimulus' missing-target message. - **Dashed target names** such as `data-copy-link-target="source-field"` produce no usable `this.…Target` property; the docs require camelCase because target names become property names. - **An action outside the controller's element** never binds, because each controller only observes `data-action` attributes inside its own scope. ## The retired syntax Before Stimulus 2, targets were written `data-target="copy-link.source"`. Stimulus 3.2.2 still resolves that form but logs a deprecation warning asking for `data-copy-link-target="source"`, and new code should use only the scoped attribute.

  • What happens if the template forgets the element a controller reads through this.sourceTarget?
    The singular getter throws an error naming the missing target and the controller, so the method stops there. `this.sourceTargets` would return an empty array instead, and `this.hasSourceTarget` returns `false`. For a target that is genuinely optional, guard with `hasSourceTarget` before touching the singular property.
  • Can one element carry two controllers and be a target of both?
    Yes. `data-controller` holds a space-separated list of identifiers, and each gets its own instance on the same element. An element can also carry `data-copy-link-target` and `data-character-counter-target` side by side, and each target attribute may list several names.
  • You meet data-target="copy-link.source" in an old view. What do you change?
    That is the pre-Stimulus-2 target syntax. Stimulus 3.2.2 still finds the element but logs a deprecation warning. Rewrite it as `data-copy-link-target="source"`, the scoped attribute the current target lookup uses.

  • Stimulus renders the controller's markup from a client-side template
  • The identifier comes from the class name the module exports
  • this.sourceTarget returns undefined when no source element exists
  • A controller can read targets anywhere on the page, not just inside its element
  • data-target="copy-link.source" is the current target syntax in Stimulus 3

Assumes Stimulus 3.2.2 (stimulus-rails 1.3.4) beside Turbo 8; the legacy data-target="identifier.name" form still resolves there but logs a deprecation warning.

open as a page

In a Rails 8.1 address book using Turbo Frames, how does editing a contact row in place work, and why must the frame ids match?

level: juniorimportance: must knowfreq 65%

basics

~20 s

A link or form inside a <turbo-frame> navigates only that frame: Turbo fetches the URL, finds the <turbo-frame> with the same id in the response and swaps its contents in. Everything else in the response is discarded, so the ids must match.

open as a page

With Turbo, what does a <turbo-stream> element do, and which actions can it apply to its target?

level: juniorimportance: must knowfreq 62%

basics

~20 s

A <turbo-stream> element is a page instruction: Turbo applies its action (append, prepend, before, after, replace, update, remove or refresh) to the element whose id is in target, or every match of the targets selector, using its <template> content.

open as a page

In a Rails 8.1 app on Turbo 8, what do turbo_refreshes_with(method: :morph, scroll: :preserve) change when a chores form redirects back to the same page?

level: middleimportance: must knowfreq 45%

basics

~20 s

They add turbo-refresh-method morph and turbo-refresh-scroll preserve meta tags. When a visit reloads the same path with the replace action, as a redirect back does, Turbo morphs the changed DOM with idiomorph and keeps the scroll position instead of swapping the body.

open as a page

In a Stimulus controller, how does static values turn data-<identifier>-<name>-value attributes into typed properties, and what happens when an attribute is missing?

level: middleimportance: must knowfreq 55%

basics

~20 s

static values maps names to types; Stimulus then generates this.nameValue, which decodes data-<identifier>-<name>-value on the controller's element, a setter that writes it back, and hasNameValue. A missing attribute yields the declared default, or the type's default.

open as a page

With Turbo Drive, why must a successful Rails form submission redirect with 303 See Other while a failed one renders with a 4xx status?

level: middleimportance: must knowfreq 72%

basics

~20 s

Turbo Drive treats a non-GET form as a visit that must end in a redirect, which it follows and renders. A 4xx or 5xx response is rendered in place, so a failed save re-renders with 422; a plain 200 render is refused.

open as a page

In a Rails controller with turbo-rails, when does format.turbo_stream answer a request, and how do you build its response?

level: middleimportance: must knowfreq 58%

basics

~10 s

format.turbo_stream answers when Accept lists text/vnd.turbo-stream.html, which Turbo adds to non-GET form submissions (or GET with data-turbo-stream); you respond with a .turbo_stream.erb template or render turbo_stream: built with the turbo_stream tag builder.

open as a page

On an exam-practice page, should a Stimulus question navigator reach the countdown timer through an outlet or through a dispatched event, and what does each choice cost?

level: seniorimportance: must knowfreq 45%

basics

~20 s

Use an outlet when the navigator commands or queries a specific countdown, such as pausing it; use a dispatched event when the countdown announces expiry to whoever listens. Outlets couple to its API and throw when absent; unheard events vanish silently.

open as a page

During a Turbo 8 morphing refresh of a chores page, what does data-turbo-permanent protect, and what client-side state can a morph still reset?

level: juniorimportance: should knowfreq 28%

basics

~20 s

data-turbo-permanent tells Turbo to leave an element untouched, so morphing skips it entirely. Anything else is made to match the server's HTML, so classes or attributes changed in the browser, such as an open menu, can be reset.

open as a page

In Hotwire Native, how do the iOS and Android shells turn a Turbo web app's link taps into native screens, and what stays web?

level: juniorimportance: should knowfreq 30%

basics

~20 s

Hotwire Native registers its own Turbo adapter, so a link tap becomes a visit proposal to native code, which pushes a native screen rendering the server's HTML in a web view. Pages stay web; navigation and gestures are native.

open as a page

In a Stimulus controller, what do static classes and properties such as this.warningClass give you over hard-coding CSS class names in JavaScript?

level: juniorimportance: should knowfreq 28%

basics

~10 s

static classes names logical styles; the view supplies the real CSS classes in data-<identifier>-<name>-class on the controller element, and the controller reads them as this.warningClass, this.warningClasses or hasWarningClass, so styling stays in the template.

open as a page

With turbo-rails, how does broadcasts_refreshes_to keep every open chores page current, and how are the resulting refreshes debounced and de-duplicated?

level: middleimportance: should knowfreq 30%

basics

~20 s

broadcasts_refreshes_to adds an after_commit callback that broadcasts a refresh stream to a named stream; pages subscribed with turbo_stream_from re-fetch and morph. A 0.5 s server debounce and a 150 ms client debounce coalesce bursts, and a request-id skips the sender's tab.

open as a page

In a Rails app serving Hotwire Native, what do hotwire_native_app? and refresh_or_redirect_to do after a habit is created in a native modal?

level: middleimportance: should knowfreq 28%

basics

~20 s

hotwire_native_app? checks the user agent for Hotwire Native or Turbo Native. refresh_or_redirect_to sends a native app to /refresh_historical_location, which dismisses the modal and reloads the screen beneath; a browser gets an ordinary redirect to the given URL.

open as a page

In a Stimulus data-action descriptor, what do default events, key filters, @window and the :prevent, :stop and :once options change?

level: middleimportance: should knowfreq 48%

basics

~20 s

A descriptor may omit the event for common elements (textarea means input, form means submit), filter keyboard events (keydown.ctrl+enter), listen on window or document (@window), and add options: :prevent and :stop call preventDefault or stopPropagation, :once passes once to addEventListener.

open as a page

In Stimulus, how do action parameters such as data-copy-link-url-param reach a controller method, and how are their values typecast?

level: middleimportance: should knowfreq 38%

basics

~20 s

Stimulus reads data-<identifier>-<name>-param attributes from the element carrying the action, camelizes the names and passes them as event.params; each value goes through JSON.parse, so numbers, booleans and objects arrive typed and anything unparsable stays a string.

open as a page

In a Rails 8.1 import-map app, how does eagerLoadControllersFrom in controllers/index.js register Stimulus controllers, and when does lazyLoadControllersFrom fit better?

level: middleimportance: should knowfreq 30%

basics

~20 s

eagerLoadControllersFrom reads the page's import map, imports every pin under controllers/ ending in _controller and registers each under an identifier derived from its path. lazyLoadControllersFrom imports a controller only when its identifier first appears in a data-controller attribute.

open as a page

In a Stimulus controller, what event does this.dispatch("expired", { detail }) send, and how does another controller's data-action receive it?

level: middleimportance: should knowfreq 38%

basics

~10 s

this.dispatch("expired") fires a bubbling, cancelable CustomEvent named countdown:expired on the controller's element and returns it. Another controller routes it with data-action="countdown:expired->question-navigator#finish" on an ancestor, or with @window when it sits elsewhere, and reads event.detail.

open as a page

In Stimulus, how does static outlets with a data-question-navigator-countdown-outlet selector give one controller another controller's instance, and when do outlet callbacks fire?

level: middleimportance: should knowfreq 35%

basics

~20 s

The host declares static outlets = ["countdown"] and puts a CSS selector in data-question-navigator-countdown-outlet; any element in the page matching it and carrying data-controller="countdown" becomes an outlet, reachable as this.countdownOutlet (the controller instance), with countdownOutletConnected/Disconnected callbacks.

open as a page

In a Stimulus controller, when does a callback such as secondsValueChanged(value, previousValue) run, and what does it receive on its first call?

level: middleimportance: should knowfreq 40%

basics

~20 s

secondsValueChanged 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.

open as a page

With Turbo Drive's page cache, why does a Rails page flash stale content on navigation, and how do turbo-cache-control and data-turbo-temporary help?

level: middleimportance: should knowfreq 35%

basics

~20 s

Turbo Drive caches the last pages visited and shows a cached copy as a preview while it fetches a fresh one, and restores from cache on Back. turbo-cache-control no-preview or no-cache opts a page out; data-turbo-temporary removes flashes first.

open as a page

With Turbo Frames, what does data-turbo-action="advance" change for a paginated contacts frame, and what must the Rails action then guarantee?

level: middleimportance: should knowfreq 30%

basics

~20 s

data-turbo-action="advance" promotes a frame navigation to a page visit: the frame updates and the browser URL moves to the frame's new URL with a history entry. The Rails action must render that URL correctly as a full page.

open as a page

With Turbo Frames in Rails 8.1, how do src and loading="lazy" defer part of a page, and what does turbo_frame_request? change on the server?

level: middleimportance: should knowfreq 45%

basics

~20 s

A <turbo-frame> with src fetches that URL after the page renders, at once by default or when it scrolls into view with loading="lazy". turbo_frame_request? tells Rails the request came from a frame, and turbo-rails then renders a minimal layout.

open as a page

With Turbo Frames, how do target="_top" and data-turbo-frame decide whether a link or form updates its own frame, another frame or the whole page?

level: middleimportance: should knowfreq 50%

basics

~20 s

Inside a frame, links and forms update that frame by default. target on the <turbo-frame> sets a default for its descendants, data-turbo-frame on a single link or form overrides it, and "_top" in either sends navigation to the whole page.

open as a page

With turbo-rails, how do turbo_stream_from in a view and broadcasts_to in a model put new kitchen tickets on every open order board?

level: middleimportance: should knowfreq 50%

basics

~20 s

turbo_stream_from @kitchen subscribes the page to a signed stream over Turbo::StreamsChannel; broadcasts_to :kitchen adds commit callbacks that, on create, update and destroy, send append, replace and remove streams rendered from the ticket's partial to that stream.

open as a page

In a Rails integration test with turbo-rails, how do you assert a Turbo Stream response and the broadcasts a model sends?

level: middleimportance: should knowfreq 28%

basics

~10 s

Send the request with as: :turbo_stream, then assert_turbo_stream action:, target: (status defaults to :ok); for broadcasts, wrap the change in assert_turbo_stream_broadcasts and run the broadcast jobs with perform_enqueued_jobs.

open as a page

For a household chores list edited by several people at once, when would you choose morphing refresh broadcasts over targeted Turbo Stream broadcasts, and why?

level: seniorimportance: should knowfreq 35%

basics

~20 s

Choose refresh broadcasts when the page is cheap to render and correctness matters more than bandwidth: every viewer re-renders the real page with their own session, so nothing drifts. Choose targeted streams for heavy pages, many viewers or high-frequency updates.

open as a page

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%

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().

open as a page

After a Rails 8.1 deploy changes CSS or JavaScript, how does data-turbo-track="reload" make tabs already open under Turbo Drive load the new assets?

level: seniorimportance: should knowfreq 30%

basics

~20 s

Turbo Drive compares the head elements marked data-turbo-track="reload" on the current and the new page. If their markup differs, as digested asset URLs do after a deploy, Turbo abandons the swap and does a full page load.

open as a page

showing 1–30 of 38