Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Oppiskele Passing Data from Server to Client Components | Section
Harjoittele
Projektit
Tietovisat & Haasteet
Visat
Haasteet
/
Building Web Apps with Next.js

bookPassing Data from Server to Client Components

Pyyhkäise näyttääksesi valikon

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.

question mark

How is data passed from a Server Component to a Client Component in Next.js?

Valitse oikea vastaus

Oliko kaikki selvää?

Miten voimme parantaa sitä?

Kiitos palautteestasi!

Osio 1. Luku 20

Kysy tekoälyä

expand

Kysy tekoälyä

ChatGPT

Kysy mitä tahansa tai kokeile jotakin ehdotetuista kysymyksistä aloittaaksesi keskustelumme

Osio 1. Luku 20
some-alt