StimulusJS: lifecycle
This course follows a Stimulus controller through its lifecycle callbacks, using controllers from one Rails app. It covers connect(), which runs when a matching element appears in the DOM, and disconnect(), which undoes what connect() started: a Chart.js instance, a pending timer or listeners on window. It explains why initialize() runs once per instance while connect() can repeat, how xxxValueChanged callbacks react to value changes, and how target callbacks track single targets. A closing lesson traces one element's full timeline and presents a Ruby challenge.
What you'll learn
- ✓When Stimulus calls connect() and how to guard async work that runs after an await
- ✓Using disconnect() to undo what connect() created, such as charts and timers
- ✓Why listeners attached to window must be removed in disconnect()
- ✓The difference between initialize(), which runs once per instance, and connect(), which can repeat
- ✓How xxxValueChanged callbacks react to value changes without a reconnect
- ✓How xxxTargetConnected and xxxTargetDisconnected track single targets inside a connected controller
connect(): where a controller's real work begins
A Stimulus controller class exists as soon as its file loads: every method is defined, every static declaration is read. That doesn't mean the controller is doing anything yet. connect() is the method Stimulus calls when an element carrying this controller's identifier shows up in the DOM. This…
Read the full lesson free →Curriculum
7 lessonsconnect(): where a controller's real work begins
connect() runs when Stimulus detects the controller's element in the DOM, and async work after it needs a guard.
disconnect(): the mirror that undoes connect()
disconnect() undoes what connect() started, destroying a Chart.js instance or clearing the flash controller's pending setTimeout.
Why disconnect() is not optional
Listeners attached to window outlive the element, so the upload progress controller removes them all in disconnect().
initialize(): once per instance, unlike connect()
initialize() runs once per controller instance, while connect() and disconnect() repeat when the same element is moved.
Value-changed callbacks: a different kind of lifecycle
xxxValueChanged callbacks fire when a value changes, so the chart controller rebuilds its chart without reconnecting.
Target-level lifecycle: a finer-grained hook
xxxTargetConnected and xxxTargetDisconnected fire when one target appears or disappears inside an already connected controller.
Putting it together: one element's full timeline
Traces one chart element through every callback and presents a Ruby challenge that computes lifecycle callback order.