Replies: 2 comments
-
Hi @Prbarmo This happens because the server renders the initial HTML with empty data ( To fix it, you can: 1. Fetch data on the serverSo both server and client render the same initial content: export default async function Home() {
const res = await fetch('https://example.com/api/message', { cache: 'no-store' });
const { message } = await res.json();
return <h1>{message}</h1>;
} In Next.js 13/14 with the App Router, you can make your component an async Server Component like above, so no hydration mismatch occurs. 2. Use a loading state placeholderRender the same placeholder on both server and client, then update with fetched data: export default function Home() {
const [data, setData] = useState('Loading...');
useEffect(() => {
fetch('/api/message')
.then(res => res.json())
.then(json => setData(json.message));
}, []);
return <h1>{data}</h1>;
} 3. Suppress hydration warningIf the content is purely client-side, mark it with <h1 suppressHydrationWarning>{data}</h1> This is more of a workaround; prefer server-rendering data when possible |
Beta Was this translation helpful? Give feedback.
-
Hi @Prbarmo the comment above is partially wrong. Notice how step 2 is just the same as your snippet. Using Yes part 1 is somewhat correct, prefer fetching data within server components. However... I am unmarking it as answer, because, using Could you share more code of what's going on? screenshots? The Next.js Dev Tools often clearly show where the error is happening. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Hi everyone,
I'm building a Next.js 14 application and I'm getting a hydration error in the console whenever I render data fetched from an API on the client side.
The error says something like:
Here's a simplified version of my code:
What's the best way to fix this hydration mismatch?
Thanks in advance!
Beta Was this translation helpful? Give feedback.
All reactions