-
Hi guys, I'm new with Next.js and read a lot in last few weeks about this awesome framework! I try to implement Dark Mode on my website, but I've got an error:
Problem: When I load website for the first time, everything is alright. Problem start when I change website theme to dark and refresh page. It doesn't happened when theme is set to light by default. So it looks, like server render first page with default light theme, but when I click on button to switch to dark mode it's rendder only on client side, change the value in localStorage but server doesn't know about that, but it should know? Question: CodeSandbox with source code: Cheers! |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
LocalStorage is only accessible on the client-side, therefore, unless the theme is default, it’ll always be mismatched on the server. A better implementation would be to save this theme information to a database and retrieve and apply this during the initial page load. If you need to persist this across pages/sessions, then look into using react’s Context API or utilize a 3rd party state manager like Redux. The database will then set this theme state accordingly. On that note, the theme in state will never be updated directly, instead you’ll want to update the database which in turn updates the theme value(s). This way, the server and client will always be 1:1. |
Beta Was this translation helpful? Give feedback.
-
Beta Was this translation helpful? Give feedback.
Solution: https://joshwcomeau.com/gatsby/dark-mode/