[Solved] How do I pass data from server component to client component in Next.js 14 app router? – Next.js

by
Ali Hasan
app-router next.js next.js13 reactjs state-management

The Solutions:

Solution 1: Using props

In the server component, serialize the data and pass it as props to the client component. In the client component, deserialize the data and use it.

Example

// page.tsx
import { YourClientComponent } from "./components/YourClientComponent";

export default async function Page() {
  const data = await fetchApi(); // Fetch data from an API

  return (
    <main>
      {/* Serialize the data in `props` before rendering the client component */}
      <YourClientComponent props={JSON.stringify(data)} />
    </main>
  );
}
// YourClientComponent.tsx
import { useMemo } from "react";

export default function YourClientComponent({ props }) {
  const data = JSON.parse(props); // Deserialize the data from `props`

  // Use the data
  return <div>{data.name}</div>;
}

Q&A

How to pass data from the server component to the client component in Next.js 13 app router?

You can pass the data as props, you just need to make sure that it is serialized.

To pass the city object to the Location component in Next.js 13 app router how can it be done?

You can pass the city object as props to the Location component.

Video Explanation:

The following video, titled "File Upload in Next.js 13 App Directory with NO libraries! Client and ...", provides additional insights and in-depth exploration related to the topics discussed in this post.

Play video

Easily upload files and then use them server-side in Next.js 13! In the past, you would need to use third-party libraries to help with this, ...