Hotwire Caching Problem
Fixing Tab Persistence with Turbo Cache Control in Stimulus
Problem:
Our current implementation relies on session storage to manage the open “tabs” a user has. The “tabs” are in quotes because this lives on a dashboard and they are actually radio buttons under the hood that are styled to look like tabs.
When a user clicks a tab, it interacts with a Stimulus controller, which captures and stores the tab’s title in session storage. In this stimulus code below, selectedOption is the tab label (Traveler expenses, Smart expenses or Pricing grid).
setSession(selectedOption) {
sessionStorage.setItem(
window.location.pathname + "_selectedOption", selectedOption
)
}
This setup allows us to remember the user’s last position when they return to the page after navigating around the app: smooth, seamless, and all-around awesome!
But is it?
We got a feature request that wants to allow users to switch tabs via a link_to from somewhere else in the app. This is where using session storage is not helpful. Instead of gracefully navigating to the correct tab, the page does exactly what we are asking of it, and shows content based on the session storage value. Not entirely helpful with this new functionality.
Solution:
Turbo! It offers a handy method to clear cached data, which allows us to fix this issue. The game plan? Add a Stimulus action that clears the cache when the link_to is clicked. This function essentially requests a fresh copy of the page from the server instead of using the cached version. Which is exactly what we want because the cached version has the session storage value for which tab and tab content to show. Here’s how that looks when added to the link_to and what it looks like in the stimulus controller:
# turbo data action on the link_to
data: { action: 'submenu#clearCache' }
# Stimulus function triggered by the data action above
clearCache() {
Turbo.cache.exemptPageFromCache();
}
With this in place, the cached session key value is no longer a problem. When the link_to is clicked, the page navigates to the correct tab like the user would expect.
Phew, crisis averted! 😮💨
If you’re looking for a team to help you discover the right thing to build and help you build it, get in touch.
Published on September 24, 2025