Persist Theme Value in Nextjs from ContextAPI
Hello. I'm trying to persist theme data in a Nextjs application (v 13.1.1 pages) using ContextApi.
Now, usually the theme state gets compiled from a
ThemeContext
and passed into the application. When the user toggles the theme, I save this value in local storage for when they come to the site again.
This fails because Nextjs is first generated on the server and there's no local storage.
What I tried
1. I tried checking for type of window
and passing the default value (light theme) if it isn't found
2. I tried useEffect
(and useLayoutEffect
) to get the theme value from local storage when the user first loads the page.
The problem with both methods is, if the user enables darkMode as their default, when the page first loads, it is initially lightMode then switches to darkMode after some milliseconds. For more context, I could provide the two files that all this is happening9 Replies
npm
next-themes
An abstraction for themes in your Next.js app.. Latest version: 0.2.1, last published: 7 months ago. Start using next-themes in your project by running
npm i next-themes
. There are 139 other projects in the npm registry using next-themes.More than light and dark mode
section @ComplexlityThanks man. I'll check it out
Oh wow. I has exactly what I want and more. Really solves all I had been fighting with lol
I just don't think it works with tailwind, only dark and light mode is supported by light mode
Oh 😔 . My application acually uses tailwind. I have only dark and light mode though. That would work?
Not what I meant lol
next-themes works with tailwind
You just asked if you could use different colors, which I interpreted as other themes than dark and light.
Okay okay. That's cool then. When I need other themes, you would've figured out a way to around it by then 🥲
What? How would I have figured out a way lol
There's probably already a way with some tailwind plugin to add themes
Yh true. I assume that'll be long process though. Not sure I'll explore that now. The site already works. I just felt it'll be good to persist it and when I tried to do that, to my greatest surprise, Nextjs refused to listen to my commands