My website has a light and dark theme. The default theme is light. If the user changes the theme to dark, it is saved to localStorage.
On the next visit/refresh at the root of my component tree, this code runs:
useLayoutEffect(() => {
let storedTheme = localStorage.getItem("theme");
if (storedTheme === "light" || storedTheme === "dark") {
// Redux action. Other components subscribe to the theme.
setTheme(storedTheme);
}
}, [setTheme]);
Say the user chose the dark theme as their preference. It works fine. However, the first render will be the light theme. The second render will be the dark theme. This causes a light to dark flicker when visiting the site.
Is there a way to ensure my first render has the set value from localStorage?