NextJs - Server vs Client Components

Single-Page Application

  • React used to render the whole Application client-side.
  • With server components, React now gives you the flexibility to choose where to render your components based on their purpose.

Server Components

  • Large dependencies that will increase Javascript bundle size can remain entirely on the server as server components.
  • Initial page load will be faster due to smaller client-side Javascript bundle size.

Client Components

  • Client Components enable you to add client-side interactivity to your application.
  • In Next.js, they are pre-rendered on the server and hydrated on the client.

Interleaved Client & Server Components

Behind the scenes, React will render all Server Components on the server first, and leave slots for Client Components to be rendered on the client.

BUT importing a Server Component in a Client Component will not work:

app/ClientComponent.js
'use client';
// This pattern will not work. You cannot import a Server Component into a Client Component
import ServerComponent from './ServerComponent';
 
export default function ClientComponent() {
  return (
    <>
      <ServerComponent />
    </>
  );
}

We can import a Server Component to a Client Component.

app/ClientComponent.js
'use client';
 
export default function ClientComponent({ children }) {
  return <>{children}</>;
}

Now we can wrap Server Component as a child or prop of a Client Component.

app/page.js
// This pattern works. You can pass a Server Component as a child or prop of a Client Component.
import ClientComponent from './ClientComponent';
import ServerComponent from './ServerComponent';
 
// Pages are Server Components by default
export default function Page() {
  return (
    <ClientComponent>
      <ServerComponent />
    </ClientComponent>
  );
}

Read More