[ColorMode] localStorageManager hydration issues
See original GitHub issueWhen not explicitly using the cookieStorageManager
, localStorageManager
is used by default. Maybe this is not the right approach.
Given a Next app, in all cases (Server, Static, SSG), as soon as changing the color mode once (= not the initial value defined in the theme) and then refreshing the page, you’ll always see a hydration warning or even visual discrepancies (e.g. a button still being in light mode when you’re in dark). Any conditional logic based on color mode is thus affected.
Why is this? During export/SSR/SSG, knowledge about a users localStorage is obviously impossible. Thus the resulting HTML and CSS will be based on initial values.
Once the user accesses the site, React will hydrate and expect the same markup. However, localStorageManager
will now no longer return undefined
as during generation, and thus, a lot of the CSS will mismatch and any HTML that renders differently based on color mode.
HTML mismatches may probably be disregarded because most apps will only have a theme toggle component render differently based on the color mode). The React docs mention for this case:
If a single element’s attribute or text content is unavoidably different between the server and the client (for example, a timestamp), you may silence the warning by adding
suppressHydrationWarning={true}
to the element. It only works one level deep, and is intended to be an escape hatch. Don’t overuse it. Unless it’s text content, React still won’t attempt to patch it up, so it may remain inconsistent until future updates.
The CSS mismatch is an issue though as it leads to e.g. <Button />
staying in light mode when we’re in dark.
Reproduction: https://codesandbox.io/s/broken-wind-l994s?file=/pages/index.js
-
copy the url of the sandbox and open it in another tab
-
open the devtools
-
change to dark mode
-
reload, check the console
-
<Button />
and<IconButton />
staying light -
<IconButton />
icon value changing
thanks for @fr3fou for making me dig deeper.
Issue Analytics
- State:
- Created 3 years ago
- Reactions:2
- Comments:21 (17 by maintainers)
Top GitHub Comments
Closing this since it will be hopefully resolved for good with the next release! 🎉
@nonissue
You can usegetServerSideProps
to access the cookies too. The issue still persists, but only for static sites where neitherlocalStorage
norcookies
are available - at build time. I’ll update the docs however, to removegetInitialProps
because that’s misleading and outdated.Scratch that, apparently a different implementation came up tonight and seems to have resolved the whole thing 🎉