Introduction to Managing State in Stimulus Code

Let’s dive deeper and explore the state maintenance functionality available in Stimulus.

Managing State in Stimulus Code

As we’ve been building our sample concert application in this course, we’ve spent a lot of time worrying about state management. As a reminder, state means the set of values the front-end needs in order to draw the correct information to the screen and properly manage user interaction. In the Hotwire and Stimulus universe, state and data are largely managed by adjusting the dataset of various DOM elements and using the browser and Stimulus controllers to work with that information. While a Hotwire and Stimulus application may use external classes to manage client-only abstractions, we probably don’t need a separate class beyond the DOM to manage the state of the application.

In this chapter, we’ll build out our calendar filter to the schedule page using the DOM to hold our client-side state. We’ll also look at how to use the MutationObserver API to detect DOM changes that might indicate client-side state updates. Later, we’ll see that a complex React app often uses separate classes to hold state values that Stimulus tries to keep in the DOM.

Using Data Values for Logic

Let’s go back to our schedule page. At the top of the page is a run of calendar dates and the “Show All” button. Earlier, in Stimulus, we added the CssController to make it so that these dates show and hide a red border to indicate which one is active. We didn’t wire that state to allow those dates to act as a filter on the schedule display, though.

The functionality we want is as follows:

  • If none of the date buttons are active, all dates are shown.

  • If any of the date buttons are active, only the dates with active buttons are shown.

  • The “Show All” button returns all buttons to the inactive state, making all dates visible.

Two factors make this feature more difficult than the previous Stimulus example. Whether an item display is dependent on not just the state of that item, but also on the state of the group as a whole. Also, the buttons affect a part of the page that is outside their own subtree of the DOM.

We can manage this in Stimulus in a few different ways. Below is the base HTML for the solution. To find it, look in the schedule show page, surrounding the calendar header code.

Get hands-on with 1200+ tech skills courses.