Theme Flicker Problem - localStorage not available on server #64391
-
Dear Developers, I hope you can help me. I have been searching all over for a good solution to this problem without luck. When I open my app, the default theme is applied for a second, before the localStorage becomes available and my saved theme is applied. Below is a video where I refresh my app to show it: flicker.problem.mp4I am looking for a good solution to avoid this or make the transition more smooth. Given that we cannot know the user's theme choice on the server side before the initial fetch, where the window object becomes available, is there then another way to access the localStorage before loading the app and setting the theme correctly? I am trying out DasiyUI for this project, where you set the theme by setting the 'data-theme' tag in the html element. Below are the relevant code snippets from my app. theme-context.tsx import { createContext, useContext, useState, useEffect } from 'react'; type ThemeContextProviderProps = { type Theme = 'cupcake' | 'dark' | null; type ThemeContext = { export const ThemeContext = createContext<ThemeContext | null>(null); export default function ThemeContextProvider({ children }: ThemeContextProviderProps) {
} export function useThemeContext() { layout.tsx const inter = Inter({ subsets: ['latin'] }); export const metadata: Metadata = { export default function RootLayout({ {children} ); } ` ThemeToggle.tsx import { useThemeContext } from '@/contexts/theme-context'; export default function ThemeToggle() {
} |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
I don't know if this is your exact problem. but theme button ui is still flicking a split second..! |
Beta Was this translation helpful? Give feedback.
-
just use cookies see my layout.tsx
there is my custom theme provider
usage
|
Beta Was this translation helpful? Give feedback.
Thank you for your answer.
I actually found a logical solution that was right in front of my eyes.
All I needed to do, was to insert the following line above the return statement in my theme-context.tsx file:
if (!theme) return null;
This prevents the page's content from loading until the correct theme has been retrieved from the local storage on the client side.
Optionally you can add a fade in animation to make the loading transition more smooth.