Haardik
Haardik

Reputation: 227

Passing data from RSC to nested child component with Next.js app router

I recently started investigating the migration of a large Pages router next.js project to the App dir - and am stuck on what feels like a very common use case with no good answer right now. Perhaps I'm just ruined by the ease of React Query at the moment - but bear with me as I try to explain my thought process.

Imagine this component tree:

LandingPage (RSC top level page.tsx) -> NavBar (Client Component) -> UserMenu (Client Component) -> SignInButton (Client Component)

The LandingPage RSC fetches data from our database, something like:

export default async function LandingPage() {
    const data = await getSiteData();
    return ( ... )
}

Now, all the way down into SignInButton - I need access to the same data - and so far I've come across these three ways of doing it:

  1. Prop Drill
  2. Make a fetch call from SignInButton to a Route Handler
  3. Use a Context or store

Back when I was on the Pages Router and using tRPC (a wrapper around React Query):

My problem with the current solutions I see are:

  1. Prop Drilling is bad. This example showcases a 3-level deep component prop drilling, but in other parts of the website this could very well be much deeper. I'd hate to do this.
  2. fetch calls seems redundant. Parent component already has this data, and I lose the benefits of TypeScript type safety when doing API Calls from inside the client components.
  3. Using Context means LandingPage will no longer be an RSC - and at this point, might as well use tRPC without using RSC anywhere

I'm not sure if I'm overthinking this - but feels like it's a common problem and there should be a way to get the client component the data of it's parent RSC's without resorting to these other solutions.

For my sanity, can you help me out and explain where I'm going wrong? Am I overlooking a fourth solution, or is one of these solutions not as bad as I think?

Thanks

Upvotes: 1

Views: 843

Answers (1)

qud
qud

Reputation: 1

probably the best bet making the server component a child of the client component.

is https://nextjs.org/docs/app/building-your-application/rendering/composition-patterns#supported-pattern-passing-server-components-to-client-components-as-props

Upvotes: 0

Related Questions