Next js 14 - prop drilling
Answered
Brown bear posted this in #help-forum
Brown bearOP
I have a simple question.
I'm using "app folder" in my Next js 14 project.
In the layout.tsx file (can also be page.tsx) I get data from the server side API and pass it to the child components using props. This gets annoying when there are many nested children components. In addition, I also need to type the data that I pass using props.
Yes, I know, if I make the same request on the server components, Next js does not send a new request, it pulls it from the cache. However, I can't do this because my children components are on the client side. How do you cope in such situations?
Thank you in advance.
I'm using "app folder" in my Next js 14 project.
In the layout.tsx file (can also be page.tsx) I get data from the server side API and pass it to the child components using props. This gets annoying when there are many nested children components. In addition, I also need to type the data that I pass using props.
Yes, I know, if I make the same request on the server components, Next js does not send a new request, it pulls it from the cache. However, I can't do this because my children components are on the client side. How do you cope in such situations?
Thank you in advance.
Answered by Arinji
Fetch data in your layout and send it to a client component which takes the data and children as props, then setup a context in the client wrapper and call that from your other children
7 Replies
If your children are client components, use a context wrapper
Fetch data in your layout and send it to a client component which takes the data and children as props, then setup a context in the client wrapper and call that from your other children
Answer
@Brown bear
Brown bearOP
Thank very much. All data appears in the "page source" and I can access it in all client components. This is very easy.
Well, let's assume that I have 100 pages and they all consist of nested components in the same way. Is it appropriate to do this application for all pages? So let me wrap all the pages (page.tsx) in the Provider (ProductsContext, ProjectsContext, UserContext, etc...) like this
Well, let's assume that I have 100 pages and they all consist of nested components in the same way. Is it appropriate to do this application for all pages? So let me wrap all the pages (page.tsx) in the Provider (ProductsContext, ProjectsContext, UserContext, etc...) like this
@Brown bear I know you marked the solution but I wanted to warn you about your final statement
It's a bad idea to wrap your whole app in a bunch of providers, remember it's a footgun, you need to limit the amount of things your wrapper wraps and the amount of data in the wrapper, it's bad for performance.
A small wrapper like just a dark theme is fine, but don't be passing a bunch of objects throughout your app