Introduction to Managing State in Stimulus Code
Let’s dive deeper and explore the state maintenance functionality available in Stimulus.
We'll cover the following
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 managing state. By managing state, I mean the set of values the front end needs in order to draw the correct information to the screen and properly manage user interaction. So far, our Stimulus page manages state by writing and reading values directly from the DOM, while our React page passes state variables up and down the component tree to ensure that all the components are working off of the same data.
As our front-end interactions become more complex, we need more complicated structures to handle access to the data. In this part of the course, I’m going to introduce a common JavaScript pattern for dealing with state called a reducer. First, we’ll explore the general pattern in our Stimulus page, then I’ll show you some core React hooks that let us interact with a reducer, and eventually, we’ll get to Redux, a reducer implementation commonly used with React.
Managing state in front-end apps is a difficult problem, and there are many, many existing solutions. In this chapter, along with other chapters ahead, I will demonstrate one way of working with data, and show you how that technique might scale.
Sharing state in Stimulus
When last we looked at the top of our Stimulus page, back in the A Little More Stimulus chapter, I said that the functionality of the calendar boxes at the top of the page wasn’t quite what I wanted. The feature we implemented was a show-hide toggle where clicking on the date at the top toggled the visibility of the date in the schedule list.
What I’d really like is for that calendar to behave more like a filter. That is, I want the behavior to be as follows:
- In the default state, where none of the days in the top row have been clicked, all the days show up in the listing.
- If a day in the calendar is clicked, we switch to a filtered view where only that day shows up. Clicking that day again restores the state where no days are selected.
- If multiple days are selected, then those days show up.
So the rule is that days that have been selected show up, and as a special case if no days have been selected, we show the whole listing rather than an empty page. The “Show All” button to the right of the list, shown in the following figure, clears all activity and, therefore, causes the entire listing to be viewed.
Get hands-on with 1400+ tech skills courses.