3

I have a new Rails project using esbuild with React. The setup is pretty standard:

<div
  id="user_edit_page"
  data-controller="user-edit-page"
>
</div>

And then a:

import { Controller } from "@hotwired/stimulus"
import React from "react";
import { createRoot } from "react-dom/client";
import UserEditPage from "../components/UserEditPage";

// Connects to data-controller="user-edit-page"
export default class extends Controller {
  connect() {
    const app = document.getElementById("user_edit_page");
    createRoot(app).render(<UserEditPage />)
  }
}

When I navigate between pages there is a really annoying flicker. It feels that Rails is serving a cached response, then re-initializes the React component, which then re-renders.

I'm assuming I can disable turbolinks and have this go away, but I was wondering if there's a nice Rails way to have things working as intended.

MB.
  • 4,167
  • 8
  • 52
  • 79

1 Answers1

2

You could disable the caching on the turbolinks in the <head> of the layout. <meta name="turbolinks-cache-control" content="no-cache">. That is one option, or I think you could create a loading screen mechanism to wait for the page to be loaded before rendering.

What version of React are you using? Are you using React-Router (if so, what version)? Could you create an async function in a useEffect hook to wait for the component to load before rendering? That would prevent the flickering.

It seems like Ruby turbolinks and React Routing do not get along with each other because the ruby link link will do a full page refresh in Rails by default.

Edit: Depending on version, you might need to change turbolinks-cache-control to turbo-cache-control

David
  • 705
  • 1
  • 6
  • 22
  • It's still happening, unfortunately, with "no-cache". Using react 18.2.0. No router, Rails' turbolinks. – MB. Oct 28 '22 at 03:21
  • Actually I'm approve this answer. The issue was the format changed to "turbo-cache-control" and "no-preview" did the trick. You might want to update the answer. – MB. Oct 28 '22 at 03:30
  • I'm glad it worked. turbolinks-cache-control vs turbo-cache-control is probably just a ruby version syntax change. I will update my answer to add that incase anyone else has the same issue. – David Oct 28 '22 at 15:13