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 happening
9 Replies
barry
barry•2y ago
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.
barry
barry•2y ago
More than light and dark mode section @Complexlity
Complexlity
Complexlity•2y ago
Thanks 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
barry
barry•2y ago
I just don't think it works with tailwind, only dark and light mode is supported by light mode
Complexlity
Complexlity•2y ago
Oh 😔 . My application acually uses tailwind. I have only dark and light mode though. That would work?
barry
barry•2y ago
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.
Complexlity
Complexlity•2y ago
Okay okay. That's cool then. When I need other themes, you would've figured out a way to around it by then 🥲
barry
barry•2y ago
What? How would I have figured out a way lol There's probably already a way with some tailwind plugin to add themes
Complexlity
Complexlity•2y ago
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
Want results from more Discord servers?
Add your server