0Pricing
React Academy · Lesson

Persisting Theme and Preventing Flash

Save theme preference to localStorage and inject a blocking script to set the theme before React loads.

The Flash of Wrong Theme Problem

When a page loads, React must download, parse, and execute JavaScript before it can read localStorage and apply the correct theme. During this gap, the browser renders using the default styles. If the user prefers dark mode but your default is light, they see a brief white flash before the theme corrects itself.

The Blocking Script Solution

The fix is an inline script placed in the document head that runs synchronously before any other code. This script reads localStorage immediately and sets data-theme on document.documentElement. Because it is a blocking script, the browser applies the attribute before painting any content.

All lessons in this course

  1. Detecting System Color Scheme
  2. CSS Variables for Theme Switching
  3. React Context for Theme State
  4. Persisting Theme and Preventing Flash
← Back to React Academy