Which approach resolves Chakra UI’s hydration mismatch for color mode?
0 reputation · 18 Jun 2024, 20:35 UTC
0 reputation · 18 Jun 2024, 20:35 UTC
Ensure that a Chakra UI application renders the correct initial theme on both server‑side and client‑side without a flash or hydration warning.
During server‑side rendering localStorage is unavailable, so the default light mode is used. After hydration the client may detect a stored preference or a system preference, causing a mismatch.
Chakra UI offers a getInitialColorMode hook that can be overridden, but the docs do not prescribe a single pattern for server‑side detection of the user’s preference. Developers must choose between cookies, meta tags, or custom logic.
getInitialColorMode to read a cookie set by the client solve the hydration mismatch?35275 reputation · 18 Jun 2024, 23:01 UTC
Override getInitialColorMode to read a cookie that stores the user’s preferred color mode. Set that cookie on the client after detecting the preference (via localStorage or window.matchMedia). This makes the server render the same mode as the client, eliminating the hydration mismatch.
getInitialColorMode on both server and client during hydration; differing values trigger a React hydration warning and a flash of the wrong theme.localStorage is unavailable, so the default light mode is used unless another source (e.g., a cookie) supplies the preference.<meta name="color-scheme"> only influences the browser’s default UI, not Chakra UI’s internal color‑mode state, so it cannot resolve the mismatch on its own.const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
const stored = localStorage.getItem('chakra-color-mode');
const mode = stored || (prefersDark ? 'dark' : 'light');
// Save the mode as a cookie (e.g., using js-cookie or document.cookie)
document.cookie = `chakra-color-mode=${mode}; path=/; SameSite=Lax; Max-Age=31536000`;
getInitialColorMode:
import { ChakraProvider, extendTheme } from '@chakra-ui/react'
function getInitialColorMode() {
// Read the cookie synchronously; return null if not found
const match = document.cookie.match(/(^| )chakra-color-mode=([^;]+)/);
return match ? match[2] : null;
}
const theme = extendTheme({})
function App() {
return (
{/* your app */}
)
}
data-chakra-color-mode attribute, matching the client’s hydration.To confirm that this approach will work for your deployment, verify whether the cookie is being sent with the initial SSR request. If the cookie is absent on the first request, the first load will still mismatch until the cookie is set on a subsequent visit.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.