I get hydration warning about data-mantine-color-scheme attribute, what does it mean?
Last updated
Example hydration warning
Error message:
Hydration failed because the server rendered HTML didn't match the client. As a result this tree will be regenerated on the client. This can happen if a SSR-ed Client Component used. > -data-mantine-color-scheme='light'
Minimal Next.js code that has this warning (Next.js used as an example, the same logic can be applied to any other framework with server-side rendering):
Why do I get hydration warning?
To fully understand this hydration warning, let's break down how server-side rendering works in React in general (Next.js, React Router, etc.):
- User navigates to the page in the browser.
- The server renders the page and sends html code to the client.
- The HTML code is parsed by the browser and rendered on the screen (at this point, JavaScript has not been executed yet; the user has only HTML code).
- JavaScript code is loaded and executed on the client.
- Hydration process starts: React compares server-rendered HTML with client-rendered HTML and tries to match them. If server-rendered HTML does not match client-rendered HTML, React will re-render the component on the client and show a warning in the console (like the one above).
Hydration mismatch errors can happen in two cases:
- Server-rendered HTML does not match client-rendered HTML
- Some code is executed on the client before React hydration starts and changes the HTML generated by the server
In the example above, the ColorSchemeScript component is used to change the data-mantine-color-scheme
attribute on the <html /> element before hydration, which causes the mismatch.
The ColorSchemeScript component executes the following JavaScript code:
This code is executed on the client before React hydration starts, which changes the HTML generated by the server and causes the warning.
How to fix hydration warning?
To fix the hydration warning, spread mantineHtmlProps on the <html /> element:
What is mantineHtmlProps?
mantineHtmlProps is an object with just two properties:
suppressHydrationWarningis used to disable hydration warning for the<html />elementdata-mantine-color-schemeis used to set the default color scheme for the app when JavaScript is disabled; it is overridden by theColorSchemeScriptcomponent on the client before hydration
Does hydration warning indicate a problem?
No, in this case, the hydration warning is expected and does not indicate a problem with the app:
the data-mantine-color-scheme attribute is changed before hydration to prevent flash of inaccurate color scheme.
How suppressHydrationWarning works?
suppressHydrationWarning is a special attribute that React uses to suppress hydration warnings for a specific element.
It does not disable hydration warnings for the whole app, only for the element with this attribute
(usually the <html /> element only).