Kevin De Baerdemaeker

Next.js Documentation

Modified 2022-10-28

Rendering

Static Rendering

With Static Rendering, both Server and Client Components can be prerendered on the server at build time. The result of the work is cached and reused on subsequent requests. The cached result can also be revalidated.

Dynamic Rendering

With Dynamic Rendering, both Server and Client Components are rendered on the server at request time. The result of the work is not cached.

Server & Client Components

Server Components

All components inside the app directory are React Server Components by default, including special files and colocated components. This allows you to automatically adopt Server Components with no extra work, and achieve great performance out of the box.

Client Components

Client Components are rendered on the client. With Next.js, Client Components can also be pre-rendered on the server and hydrated on the client.

To use a Client Component, create a file inside app and add the "use client" directive as the first line of code.

'use client';

import { useState } from 'react';

export default function Counter() {
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>Click me</button>
    </div>
  );
}

Recommendations

Server and Client Components can be interleaved in the same component tree. Behind the scenes, React will merge the work of both environments.

However, in React, there's a restriction around importing Server Components inside Client Components because Server Components might have server-only code (e.g. database or filesystem utilities).

For example, importing a Server Component in a Client Component will not work:

'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 />
    </>
  );
}

You can pass a Server Component as a child or prop of a Client Component. You can do this by wrapping both components in another Server Component. For example:

// ✅ 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>
  );
}

With this pattern, React will know it needs to render <ServerComponent /> on the server before sending the result (which doesn't contain any server-only code) to the client. From the Client Component's perspective, its child will be already rendered.

Metadata

Creator(s)

  • Source
  • Recommended By

    Reason