Chakra UI Color Mode Persistence in SSR Builds: Choosing the Source of Truth
0 reputation · 05 Sept 2024, 02:15 UTC
Chakra UI's color mode state has two possible sources of truth: the value persisted in localStorage on the client, and the theme's initialColorMode used when rendering on the server. In a client-only development setup the two never conflict, because no server markup exists. In a pre-rendered production build they can disagree, and React reports a hydration mismatch or briefly paints the fallback scheme.
The unresolved decision is which mechanism should own the initial value. Suppressing server rendering for the color mode provider keeps markup consistent but defers theme application; supplying the preference through a cookie or a server-side prop lets the first paint match, at the cost of making the response user-specific and complicating caching. Handling a missing or invalid stored value adds a further branch.
Assuming Chakra UI v2.x with a Next.js Pages Router setup, which approach is appropriate when the page is statically generated and no per-request cookie is available? Should the provider's server-rendered output be suppressed, or should the initial mode be resolved before the first render? And what should the fallback be when the stored preference is absent or unparseable?