How to Ignore React Hydration Errors
To ignore any server-side rendering (SSR) hydration error in React, use the suppressHydrationWarning
prop on any element:
function Page() {
return (
<html suppressHydrationWarning>
<head />
<body />
</html>
);
}
The suppressHydrationWarning
prop will prevent any errors relating from a mismatch between server and client HTML. This only applies for the specific element for which the prop is set on.
Why hydration errors happen
Hydration errors happen when the HTML rendered on the server does not match the HTML rendered on the client. This can happen for a number of reasons, some of which are entirely valid.
When to ignore hydration errors
Some hydration errors are unavoidable and should be ignored. For example errors from browser extensions or inline JS. Such hydration errors should be ignored and the suppressHydrationWarning
prop is the perfect solution for this
Browser extensions
Some browser extensions add elements or attributes to the DOM
DOM modifying JS in the document head
A good example of this is toggling color-schemes by adding a class to the <body>
tag using an inline <script>
tag inside <head>
element
Drawbacks of ignoring hydration errors
Ignoring hydration errors can be dangerous. It can hide bugs in your code and cause unexpected behavior. Generally speaking, you want your server HTML and initial client HTML to match up.
Thankfully the suppressHydrationWarning
only acts on the specific element it's applied on. Hence the scope of the error suppression is limited
References
Comments