How to Switch Themes in Next.js Without Flickering - CSS/SCSS
Unanswered
Mackenzie River Husky posted this in #help-forum
Mackenzie River HuskyOP
Hi everyone!
I'm trying to implement theme switching in a Next.js app using CSS/SCSS. The problem I'm facing is that even though I use the 'use client' directive, I keep getting this error when trying to initialize state from
I want to achieve a seamless theme switch without any flickering, similar to how it's done on the Vercel website. If I load the theme from
I want to solve this problem without using a loading screen, and I would greatly appreciate any help. If there's a native CSS/HTML solution or a better best practice than using
I'm trying to implement theme switching in a Next.js app using CSS/SCSS. The problem I'm facing is that even though I use the 'use client' directive, I keep getting this error when trying to initialize state from
localStorage:⨯ components\header\ThemeToggle.tsx (6:40) @ localStorage
⨯ ReferenceError: localStorage is not definedI want to achieve a seamless theme switch without any flickering, similar to how it's done on the Vercel website. If I load the theme from
localStorage inside a useEffect, I need to provide a default theme for the state, which then switches once the value is loaded from localStorage or cookies. However, if I initialize the state directly with localStorage, I get an error and the screen momentarily flashes white during loading.I want to solve this problem without using a loading screen, and I would greatly appreciate any help. If there's a native CSS/HTML solution or a better best practice than using
localStorage, please share your insights. Thank you!2 Replies
I personally use [next-themes](https://github.com/pacocoursey/next-themes)
Mackenzie River HuskyOP
Oh boy, you are fast! Thank you very much, I tested it quickly, and it works perfectly.