/layout.js @ 1688734135495 [Home]

Disabling SSR for Client Components

This content is generated client-side. Datestamp:

The above component is a client component that does not trigger the hydration errors. The source code is below:

'use client'
import {useEffect, useState} from "react";

export default ()=>{
  const [isServer,setServer] = useState(true);
  useEffect(setServer,[]);

  return (
      <p class={"client-component"}>
        This content is generated client-side. Datestamp: {isServer ? '' : Date.now()}
      </p>
  );
}

Key Points:

  1. The component uses a local state variable to track whether it's running on the server or not
  2. By default, it is true. When it runs on the server, it renders with isServer==true
  3. useEffect does not run in SSR. So the setServer() is never called during SSR. isServer remains true.
  4. When the component first renders on the browser, isServer==true because useEffect hasn't run yet.
  5. The output in the client will match the output on the server (empty string), so the hydration error is not triggered.
  6. After initial render, useEffect is triggered and setServer is called, setting isServer to undefined, which evaluates to false.
  7. Since state has changed, the component renders again, this time displaying the Date.now() output

This approach lets the component control how it handles SSR.

'use client'

Let's revisit this - What does this really mean?

But what if a reusable Client Component doesn't do this itself, and causes hydration errors because of SSR?

Disabling Component SSR Server-Side