Turbo causing page flicker

Hi all I have a rails 7.2.2 app setup using importmaps and the default turbo setup. The behavior I am trying to understand is as follows:

I have an index page of Posts (/posts) with a search form. It has a mapbox.js map on it that is controlled by a stimulus controller called MapController. Running a search works fine and turbo fires (/posts?q=mypost) and renders the matching posts. But when I click a top level navigation link_to back to posts_path (/posts) MapController’s connect function is called twice causing the map to flicker.

My understanding of this is that turbo drive renders a preview of the previously cached /posts html since i’ve already been there and connect() gets called after the preview loads. THEN when turbo gets the updated response for (/posts) connect() gets called again even though the result was probably the same as the cached preview.

Clearly the way i’m using things this is expected behavior. The solution I was thinking of was I could perhaps have some hash of the post objects on the page so that I could add a guard clause inside MapController.js connect() function and not have the mapbox map reload if the hash hasn’t changed, but it seemed complicated and I thought I might be missing something basic about the Turbo and Stimulus lifecycle that could help me here.

Curious to know best practices for this kind of thing.

I ran into a similar issue with a chartjs canvas. My solution was to add data-turbo-permanent on the flickering element and refresh the element with the stimulus controller in the connect callback. You can see it in jch.app, view source and look for the id="networthChartContainer" and networth_chart_controller.js for the stimulus controller.