Passing Data from Server to Client Components
Desliza para mostrar el menú
One of the main advantages of Next.js is that you can fetch data on the server and then pass it to interactive components in the browser.
This allows you to combine the performance of Server Components with the interactivity of Client Components.
Example - Fetch Data on the Server
import Counter from "./Counter";
export default async function Page() {
const data = { initialCount: 5 };
return (
<div>
<h1>Dashboard</h1>
<Counter initialCount={data.initialCount} />
</div>
);
}
This page is a Server Component. It prepares data and passes it as props.
Client Component Receiving Data
"use client";
import { useState } from "react";
export default function Counter({ initialCount }) {
const [count, setCount] = useState(initialCount);
return (
<button onClick={() => setCount(count + 1)}>
Count: {count}
</button>
);
}
The client component receives the data and uses it to initialize state.
How It Works
The Server Component runs first and prepares the data. Then the Client Component receives this data as props and becomes interactive in the browser.
This creates a clear flow:
- Server → fetch and prepare data;
- Client → display and interact with data.
Important Rule
Data passed from server to client must be serializable.
This means you can pass numbers, strings, arrays, objects.
You should not pass functions, class instances, complex non-serializable values.
Why This Pattern Is Important
This pattern allows you to:
- Fetch data securely on the server;
- Reduce client-side logic;
- Keep performance high;
- Still build interactive UI.
It is one of the most powerful patterns in Next.js.
¡Gracias por tus comentarios!
Pregunte a AI
Pregunte a AI
Pregunte lo que quiera o pruebe una de las preguntas sugeridas para comenzar nuestra charla