DEV Community

Cover image for How to Fix FOUT (Flash of Unstyled Text) in React
Firmansyah Yanuar
Firmansyah Yanuar

Posted on

How to Fix FOUT (Flash of Unstyled Text) in React

FOUT

Can you see font is changing from default to expected font? That's called FOUT (Flash of Unstyled Text). This happend cause your browser is rendered element before your font has loaded. It makes your website look cheap and you look like a beginner. šŸ˜Ÿ

Be grateful because in 2021 there is already an API to solve this problem. The name is FontFaceSet API, you can check the documentation here.

Let's get started!

#0 FYI

I am using fontsource to import my external font. Just because, I am using the gatsby framework. It doesn't matter what you use, because this method works on any framework. Including the non-react framework.

import "@fontsource/merriweather"
Enter fullscreen mode Exit fullscreen mode

#1 Create state

const [isReady, setIsReady] = useState(false);
Enter fullscreen mode Exit fullscreen mode

First we create a state to store the state whether the website is ready to render or not.

return (isReady &&
    <div>
        {/* Your component goes here */}
    </div>
  )
Enter fullscreen mode Exit fullscreen mode

Don't forget to add a condition if the state shows it's not ready, then don't render the element.

#2 Check & Load fonts

To check the font we use FontFaceSet as follows:

useEffect(() => {
  document.fonts.load("12px Merriweather").then(() => setIsReady(true));
}, [])
Enter fullscreen mode Exit fullscreen mode

Merriweather is fontface name, you can change that. 12px is dummy fontSize to check. The following line of code is a Promise so that we can add commands when the font has been successfully loaded.

#3 And wallaaaaa...

Result

Thanks for your time to read this post. This is my first post on dev.to, i hope i can keep on writing on this platform šŸ˜† . If you don't mind please give a reaction to support me. šŸ’—

Top comments (4)

Collapse
 
okkarmin profile image
OkkarMin

Could another issue be that search engine crawlers might not work properly? Because of the delay?

Collapse
 
fyfirman profile image
Firmansyah Yanuar • Edited

Yes, SEO also have some bugs because of the delay. After i implement this method, i think best way to handle FOUT problem is configurating the default font. So user can see other default font that look similar with your styled font. Maybe i will update my post. Thanks for asking šŸ™

Collapse
 
fahmifan profile image
fahmi irfan

Well, the downside of this technique is higher loading time. Is there a way to swap the font, like swaps placeholder image with the real one?

Collapse
 
fyfirman profile image
Firmansyah Yanuar • Edited

Yeah, maybe for better UX i think that technique can combine with skeleton component. It will better than just wait without 'loading indicator'. Thanks for the comment.