Sub topic 10
When to use suppressHydrationWarning
This chapter assumes you can write function components with useState and useEffect, and that you have seen a hydration mismatch warning in a server-rendered React app. You should know how hydrateRoot attaches React to server HTML. The earlier chapters on mismatch causes and their fixes cover the rest.
What the prop does
suppressHydrationWarning is a boolean prop you can put on any DOM element, such as <div>, <time> or <html>. During hydration, React compares the server HTML with what the client render produced. If the attributes or text of an element with this prop differ, React skips the warning for that element.
The prop only silences the warning. It does not make the two sides agree. React does not promise to repair text or attributes on that element, so the user may keep seeing the server value until a later update changes it. Treat it as a way to say "I know this differs, and that is intended."
The prop has three limits.
- One level deep. It covers the text content and attributes of the element that carries it. Mismatches in child elements still warn.
- DOM elements only. Putting it on a component you wrote does nothing unless that component passes it to a DOM element.
- Content and attributes only. It does not cover structural differences, such as the server rendering a
<span>where the client renders a<div>. Structure mismatches still force React to discard server DOM and render on the client.
Legitimate uses
Use the prop when the difference is expected and cannot be avoided cheaply. In practice that is a short list.
| Case | Why the mismatch is expected | Where the prop goes |
|---|---|---|
| Formatted dates and times | The server and browser differ in locale and time zone | The `<time>` element or text wrapper |
| Theme class set before hydration | An inline script reads `localStorage` and changes `<html>` early | The `<html>` element |
| Attributes written by extensions | Browser extensions add attributes to `<html>` or `<body>` | The element being changed |
| Values you cannot make deterministic | A third-party widget id or timestamp, where the text is not important | The element showing the value |
Formatted dates
A server in UTC and a browser in another time zone print different strings for the same instant. Here the text is a display detail, so the mismatch is harmless.
export default function PostDate({ iso }) {
return (
<time dateTime={iso} suppressHydrationWarning>
{new Date(iso).toLocaleString()}
</time>
);
}The dateTime attribute is identical on both sides because it comes from the prop. Only the visible text differs, and the prop is on the same element as that text, so the one-level limit is satisfied.
If the correct local time matters to users, do not stop here. A user may keep seeing the server's UTC string. In that case, render a placeholder first and fill in the local time in an effect, as in the chapter on client-only effects.
Theme set by an inline script
A common flash-of-wrong-theme fix is a small script in the document that runs before React hydrates. The script adds a class to <html> based on saved preferences. The server cannot know that class, so the attributes differ.
export default function App() {
const themeScript = `
try {
var theme = localStorage.getItem('theme');
if (theme === 'dark') {
document.documentElement.classList.add('dark');
}
} catch (e) {}
`;
return (
<html lang="en" suppressHydrationWarning>
<head>
<meta charSet="utf-8" />
<title>My app</title>
<script dangerouslySetInnerHTML={{ __html: themeScript }} />
</head>
<body>
<h1>Hello</h1>
</body>
</html>
);
}Hydrate this with hydrateRoot(document, <App />), as in the earlier chapter. The prop on <html> covers the class attribute that the script changed. It does not cover the <body> or anything below it. Those still hydrate and warn normally, which is what you want.
What it does not fix
The prop is often applied too high or too early. These are the usual mistakes.
Wrapping a parent
function Dashboard({ user }) {
// The prop silences only this div's own attributes and direct text.
return (
<div suppressHydrationWarning>
<h2>{new Date().toLocaleTimeString()}</h2>
<p>{user.name}</p>
</div>
);
}The <h2> still warns, because the mismatch is in a child. Move the prop to the element whose content differs:
function Dashboard({ user }) {
return (
<div>
<h2 suppressHydrationWarning>{new Date().toLocaleTimeString()}</h2>
<p>{user.name}</p>
</div>
);
}Different structure
If the client renders different elements than the server did, for example a branch on typeof window, the prop cannot help. React cannot map the trees onto each other. Fix the cause by rendering the same tree first and switching after mount with an effect.
Hiding real bugs
A warning is a signal that server and client logic disagree. Suppressing it on an element that should match, such as a product price, leaves a visible bug with no console message. Later changes to that code will not warn you either.
Not reporting errors
The prop removes a warning. It does not remove the mismatch cost for unrelated elements. Keep onRecoverableError set up on hydrateRoot so that real mismatches elsewhere still reach your logs.
Deciding whether to use it
Try the other fixes first. They keep the page correct. The prop only keeps the console quiet.
A short checklist before you add the prop:
- Name the exact element and the exact text or attribute that differs.
- Confirm that users do not depend on the server's value being replaced.
- Place the prop on that element and nowhere above it.
- Add a comment explaining why the difference is expected.
Checking the result
After adding the prop, reload the page with the console open. The warning for that element should be gone, and other warnings should remain. If a warning disappears that you did not target, the prop is probably too high in the tree.
Also check what the user sees. For the date example, compare the text right after load with the text after a re-render. If the two differ and that matters, switch to the effect pattern.
import { useEffect, useState } from 'react';
export default function LocalTime({ iso }) {
const [text, setText] = useState(null);
useEffect(() => {
setText(new Date(iso).toLocaleString());
}, [iso]);
return <time dateTime={iso}>{text ?? ''}</time>;
}This version renders an empty string on the server and on the first client render, so both match. The local time appears after hydration. It needs no suppression, and the user always ends up with the local value.
Summary of rules
- It silences a warning. It does not repair the DOM.
- It works one level deep, on text and attributes of the marked element.
- It cannot cover structural differences.
- Valid uses are dates, a pre-hydration theme script on
<html>, and attributes changed by extensions. - When the correct client value matters, use an effect instead.
Exercise
A page renders <section suppressHydrationWarning><p>{Math.random()}</p></section> and still logs a hydration warning. Why does the warning remain, and how would you fix it if the random number must not differ between server and client?
Show answer
The prop covers only the attributes and direct text of the <section>. The differing text is in the child <p>, so the warning stays. If the value must match, do not render Math.random() during render. Generate it on the server and pass it down as a prop, or render a placeholder and set the value in useEffect. If the difference is truly harmless, move suppressHydrationWarning to the <p> element.
Exercise
You add an inline script that sets a data-theme attribute on <html> before React hydrates. The console warns about the <html> attribute. Where should the prop go, and does it also silence mismatches inside <body>?
Show answer
Put suppressHydrationWarning on the <html> element. It does not silence mismatches inside <body>, because the prop works only one level deep. Mismatches in <body> or its children will still warn.