Fixing Gatsby images or content flashing on load
If either of these sound familiar to you, then you are having a hydration issue with Gatsby:
- Images flashing / flickering / blinking / reloading after page has loaded (usually happens with Gatsby Plugin Image)
- Some elements on the page flash / flicker / blink for a moment when loading the page
The cause for this issue is that the initial HTML render does not match what React expects. When you visit a Gatsby site, the first thing you receive is the HTML for the page – the initial render. Then React loads and does its hydration, meaning that it adds its own event handlers on the existing HTML. If React's own hydration render doesn't match the original HTML, then React decides to replace the entire original DOM (the static HTML) with its own client side render. This means that the original HTML will be replaced by what React generates. This makes the images or content blink for a quick moment as the content gets replaced and some page loading effets might happen again, such as image loading fade animations.
Update: Ready a quick guide about React hydration error: React Hydration Error Explained in 2 Minutes. You should check it out!
You can first check out for console errors on the production build of your site. If you are having the hydration error, you should see the following errors: "Minified React error #423" and "Minified React error #418". The error 418 tells you that the initial HTML does not match what React expects, and error 423 lets you know that hydration failed and that React switched to client rendering (abandoned the initial HTML).
There are a couple more fixed on the React Hydration Error Explained in 2 Minutes article.
Now when you open up the console on development build of your site (
gatsby develop), you should see what the issue with the React render is. In my case, it was that I didn't include a
<tbody> on my table element. With HTML, those two tags can to my knowledge be not included, but apparently in React you must have them inside the table. I added the missing
<tbody>elements my table, and the errors went away and image flickering got fixed!
So what you should do, is to open up the console on your development build and see if you have some errors logged in that relate to the DOM. If there are errors, follow whatever advice there is and try to build your site again. If the production site doesn't flicker and the console is empty, then the hydration error has been fixed!