Component Composition and Passing Data Between Components

Next.js Course: Beginner to Advanced with Examples · Components and Layouts · 6 min read · Updated

Pass small pieces down

  1. The server page reads or builds the data.
  2. It passes the parts into a reusable Card through props and children.
  3. Only the small value the button needs, here a number, goes on to the Client Component.
  4. The visitor clicks, and the client part updates its own state.

A good component is like a good Lego brick. It does one clear job, it fits with other bricks, and you can use it many times in different models. Building a page by joining small components is called composition. In this lesson we practise it in Next.js, and we learn the one new rule the App Router adds: what can travel from a Server Component to a Client Component.

Reusable components

Put a component in its own file, give it clear props, and use it wherever it is needed. This is plain React, and it works the same way in Next.js. A shared component usually lives in a components folder at the top of the project. A component used by one route only can sit next to that route.

type CardProps = {
  title: string;
  children: React.ReactNode;
};

export default function Card({ title, children }: CardProps) {
  return (
    <section className="rounded border p-4">
      <h2 className="font-semibold">{title}</h2>
      {children}
    </section>
  );
}
  • Props are the inputs. Give each one a clear name and a type.
  • children is whatever you put between the opening and closing tags. It makes a component a flexible container.
  • One job per component. If a component is hard to name, it may be doing too much.

Passing data from parent to child

Data moves down the tree through props. A parent gives a value, and the child shows it. In our article example the Server Component ArticleCard passed a starting number to the Client Component LikeButton.

import LikeButton from "./LikeButton";

// A Server Component: it can be async and read data directly.
export default async function ArticleCard() {
  const article = { title: "Server and client together", likes: 3 };
  return (
    <article>
      <h2>{article.title}</h2>
      <LikeButton start={article.likes} />
    </article>
  );
}
"use client";

import { useState } from "react";

export default function LikeButton({ start }: { start: number }) {
  const [likes, setLikes] = useState(start);
  return <button onClick={() => setLikes(likes + 1)}>Likes: {likes}</button>;
}

The parent reads or builds the data on the server and sends only the number to the browser. That is a nice pattern. Fetch the data in a Server Component and pass the small pieces that the interactive part needs.

What can cross from server to client?

When a Server Component passes a prop to a Client Component, the value has to travel from the server to the browser. So it must be something that can be turned into a message. React calls this being serialisable. A few clear rules help.

  • Allowed: strings, numbers, booleans, null, arrays and plain objects, dates, and other Server Components as children.
  • Not allowed: ordinary functions, class instances and objects that have methods. You cannot send an onClick function from a server file to a client file.
  • An exception: a Server Action, which you will meet in the forms module, can be passed down because it is a special kind of function.

If you break the rule, Next.js shows an error that says functions cannot be passed to Client Components. The fix is to define the function inside the Client Component, or to move the interaction into a small client file.

// Wrong: a server page cannot give a plain function to a client button
// <LikeButton onLike={() => console.log("liked")} />

// Right: the client component owns its own handler
"use client";
export default function LikeButton() {
  function handleClick() {
    console.log("liked");
  }
  return <button onClick={handleClick}>Like</button>;
}

Passing data upwards and sideways

Data does not go up from child to parent in React. The child calls a function that the parent gave, and the parent changes its own state. This works between Client Components. Between two Server Components there is no state at all, so you usually fetch the data in a shared parent and pass it down, or you read the same data in both places. In the next module you will see that Next.js remembers repeated fetches during one request, so reading in both places is cheap.

Composition patterns that work well

  • Wrapper with children. A Client Component wraps server content, as in the modal example in lesson 10.
  • Small client islands. Keep a big page on the server and sprinkle small interactive parts.
  • Pass slots as props. A layout component can take props such as header and sidebar that are React nodes.
  • Keep data fetching high. A page or layout reads the data, and the small components just draw it.

Mistakes to avoid

  • Marking a whole page as use client because one button needs state.
  • Passing a huge object to a client component when it needs one field. Everything you pass is sent to the browser.
  • Putting a secret into props. Props to a client component become visible in the page.
  • Copying props into state without a reason. Use the prop directly.

Your task

  1. Build a Card component with title and children and use it three times on one page.
  2. Make an async Server Component that holds a fake article object and passes only the title and the likes to a client button.
  3. Deliberately pass a function from a server page to a client component. Read the error, then fix it.
  4. Look at your own project and find one big client component that could be split.

How to check it worked

  • You can use the same Card with different content.
  • You can say which kinds of values can go from server to client.
  • The error about passing functions makes sense to you.

Frequently asked questions

Can I pass a function from a Server Component to a Client Component?

Not a normal function. Props must be values that can be sent as a message. Define the handler inside the Client Component, or use a Server Action for forms.

Where should I fetch data, in the parent or in the child?

Usually in a Server Component high in the tree, and pass the pieces down. Small components then stay simple and easy to reuse.

Is it bad to pass a large object as a prop?

To a Client Component it can be, because everything in props is sent to the browser. Pass only what the component needs.