I have built react.js site from create-react-app. But in production mode, there is FOUC because styles are loaded after html is rendered.
Is there any way to resolve this? I have been searching google for answers, but haven't found proper one yet.
I have built react.js site from create-react-app. But in production mode, there is FOUC because styles are loaded after html is rendered.
Is there any way to resolve this? I have been searching google for answers, but haven't found proper one yet.
FOUC
FOUC - so called Flash of Unstyled Content can be as very problematic as so many tries of solving this issue.
To the point
Let's consider following configuration of routing (react-router):
where
PageLayout
is a simple hoc, containing div wrapper withpage-layout
class and returning it's children.Now, let's focus on the component rendering based on route. Usually you would use as
component
prop a ReactCompoment
. But in our case we need to get it dynamically, to apply feature which helps us to avoid FOUC. So our code will look like this:to clarify let's also show how
asyncRoute.js
module looks like:Why
setTimeout
?Just because we need to remove
fouc
class in the second tick. Otherwise it would happen in the same as rendering the Component. So it won't work.As you can see in the
AsyncImport
component we modify react root container by addingfouc
class. So HTML for clarity:and another piece of puzzle:
sass to apply when importing of specific component (ie.:
Home
,Example
) takes place.Why not
display: none
?Because we want to have all components which rely on parent width, height or any other css rule to be properly rendered.
How it works?
The main assumption was to hide all elements until compoment gets ready to show us rendered content. First it fires
asyncRoute
function which shows usLoader
untilComponent
mounts and renders. In the meantime inAsyncImport
we switch visibility of content by using a classfouc
on react root DOM element. When everything loads, it's time to show everything up, so we remove that class.Hope that helps!
Thanks to
This article, which idea of dynamic import has been taken (I think) from react-loadable.
Source
https://turkus.github.io/2018/06/06/fouc-react/