Sobes.tech
Middle

What is a server component and a client component in Next.js? How is a client component declared? Is it possible to embed a server component into a client component and vice versa?

sobes.tech AI

Answer from AI

In Next.js, components can be server components and client components.

  • Server component is rendered on the server and does not contain client state or effects. It can directly access databases and APIs without passing data to the client.

  • Client component is rendered on the client, supports state, React hooks (e.g., useState, useEffect), and user interaction.

To declare a client component, add the following directive at the beginning of the file:

'use client';

import React, { useState } from 'react';

export default function ClientComponent() {
  const [count, setCount] = useState(0);
  return <button onClick={() => setCount(count + 1)}>Clicked {count} times</button>;
}

Nesting:

  • A server component can embed a client component, as the server component is rendered on the server and can send a client component for rendering on the client.
  • A client component cannot directly contain a server component, as server components do not support client hooks and state.

Thus, nesting is only possible from server to client.

What is a server component and a client component in… - sobes.tech