I'm getting confused while using server and client components
Unanswered
Billy posted this in #help-forum
BillyOP
Recently completed the Nextjs official tutorial, and stuck with how to use server component in client component and how to use client component inside server component.
in the official tutorial I noticed a component for
that was a part of a solution but how to pass it directly into the
in the official tutorial I noticed a component for
/app/invoices/create/page.tsx they used it as a server component with async function as following.that was a part of a solution but how to pass it directly into the
<Form/> Client Component without passing it as a prop from the parent Server Component /app/invoices/create/page.tsx using Hooks or what every way to make it clearer and customizable.import Form from "@/app/ui/invoices/create-form";
import Breadcrumbs from "@/app/ui/invoices/breadcrumbs";
import { fetchCustomers } from "@/app/lib/data";
export default async function Page() {
const customers = await fetchCustomers();
return (
<main>
<Breadcrumbs
breadcrumbs={[
{ label: "Invoices", href: "/dashboard/invoices" },
{
label: "Create Invoice",
href: "/dashboard/invoices/create",
active: true,
},
]}
/>
<Form customers={customers} />
</main>
);
}1 Reply
Giant resin bee
If there is no deep nesting, just directly pass the props. It's completely fine
Otherwise, you can create a Context Provder, wrap the children with it, prefill it with the data from server and then get the data from the context inside the client component
something like this, consider this the server component
but i would only recommend this if you need to use the server data in multiple client components which may have considerable depth of nesting
Otherwise, you can create a Context Provder, wrap the children with it, prefill it with the data from server and then get the data from the context inside the client component
something like this, consider this the server component
export default async function ServerComponent(){
const data = await fetchData();
return <YourContextProvider data={data}>
// your client component
</YourContextProvider>
}
export default function ClientComponent(){
const {data} = useYourContext();
return <div>{data}</div>
}but i would only recommend this if you need to use the server data in multiple client components which may have considerable depth of nesting