Dark mode example with SSR and SSG #21982
Replies: 3 comments
-
I just made this comment in another discussion and the challenge is somewhat similar, but also somewhat different. Dark mode switches comes in two types: 1. storing the user preference "somewhere" and restoring it on page load; or 2. detecting the user environment with the It's the second option that's most similar to my other comment and the full answer is surprising complex. You may not be able to avoid a flicker when using SSR/SSG if the initial page load always renders as one colour scheme then some logic within the client switches to the other colour scheme. This can be especially apparent when loading a localstorage value into a hook to manage the active mode (which is a pretty common way to do it) because the server doesn't have this value at request time. One option could be store the user preference in a cookie so that it is sent in request headers and use My recommendation if you want something that works for both SSR and SSG, doesn't trigger a re-render of styles as some user preference gets loaded, and follows the users' system setting... is through CSS variables. There's plenty of resources out there for achieving this with a variety of styling approaches:
But the key takeaway for each of these is always: render the exact same output on the server as the client. Let CSS do the heavy-lifting for you; that's what it's there for. |
Beta Was this translation helpful? Give feedback.
-
Yeah, I have manage to make it work nicely with both SSR and SSG using CSS variables and I think that's one of the best options. In fact, I give all credits to Josh Comeau. As you said, this is not straight forward so I want to know if you think this is a relevant subject for making a example and merging into examples folder |
Beta Was this translation helpful? Give feedback.
-
CSS variables are indeed great solution. But what if I use TailwindCSS? |
Beta Was this translation helpful? Give feedback.
-
Is there any example showing how to implement dark mode theme with SSR and SSG and saving the user preference mode (light or dark) without suffering a flicker (where the user sees the wrong colors for a brief moment)?
If there is not, I would like to implement one and send a PR, if you think that's relevant.
Beta Was this translation helpful? Give feedback.
All reactions