Home > Software engineering >  How to stop react application from flashing on every refresh
How to stop react application from flashing on every refresh

Time:09-11

My question has to do with all of the react applications i have created always end up flashing a blank page just for a split second before showing all the content. If I view the renders using lighthouse for example I can clearly see how the first 1-3 renders or so are just blank white pages. However I notice that all the pages build upon react that I find online does not flash on refresh and when viewing the renders on lighthouse you can see that the first renders have content on them. I'm wondering if I'm missing something or what I should do to fix this. Thanks.

CodePudding user response:

Probably you are fetching some data asynchronously somewhere high up in the component tree and you are returning null until it arrives.

Theres not much you can do about that other than considering not returning null and showing some loading state. Or you could use nextjs or remix or something which has server side rendering of the react components before your JS even loads on the browser side. The reason you don't see it on other sites will be:

  • They dont need to fetch any data over the API.
  • They do fetch data, but their API is faster than yours.
  • They inject whatever the data is needed to load the page into the HTML on the server side and then the JS app collects it from their. This is often a useful trick.
  • They are using something like nextjs -- which prerenders the content on the server first.
  • They have moved their loading states to be scoped to the components that require the data, instead of blocking the whole app. Not always possible if its checking auth or something since thats a global thing.

I assure you though there will be plenty of apps that also do have this problem. Its one of the downsides to single page apps.

CodePudding user response:

Maybe you can apply loaders like this one https://mhnpd.github.io/react-loader-spinner/docs/components/progress-bar

The logic is like this, as long as the React is not ready yet you can call the spinner / loader function. Then when React is ready you just output everything that is rendered.

Here's a question that tackles it React - Display loading screen while DOM is rendering?

  • Related