reactjslocal-storagedarkmodeflashing

Can't Fix React Dark Mode Flashing


I am facing a frustrating issue with implementing dark mode into my React application. The application reads from localStorage and applies the theme preferred by the user (this is all done by use-dark-mode). Unfortunately, everytime the user opens the page, the default theme flashes before dark mode is enabled.

Now, I've looked around the internet and found out, that simply placing specific code (as seen here) in a <script> tag just after <body> resolves the issue.

Problem is, nothing seems to fix this unpleasant flash and it occurs across all browsers. I've tried moving the script inside the <head> tag and even running it with window.onload, but nothing seemed to work.

Has anyone experienced a problem like this? What's the best approach to fix this flash? Thanks a lot in advance!

Here's a link to the GitHub repository. Note: I'm not using any server-side rendering.


Solution

  • As it turns out, the fix is really easy. In your index.html add a bit of style inside the <head> tag.

    <style type="text/css">
      body.light-mode {
        background-color: #F9FAFC;
      }
    
      body.dark-mode {
        background-color: #1A1A1A;
      }
    </style>