Next.js Discord

Discord Forum

What pattern should I use to pass a global object into multiple nested components?

Unanswered
୧ʕ•̀ᴥ•́ʔ୨ posted this in #help-forum
Open in Discord
But it's a static object so it's not really state, just a large json object. I could use a context provider but that's probably overkill and not what context providers are intended for. On the other hand I don't want to prop drill the object into all the components. Any ideas?

17 Replies

Korat
I don't think a context provider is overkill. I think it's exactly what you're looking for. Just be sure to create the provider outside of your layout.tsx file and mark the provider with "use client" and you should be good to go.
A context provider would force all components that use it to be client components though
Would there be a way to pass data into server components without prop drilling?
Korat
Umm, I don't believe that is true but I'll double check
Yeah, that isn't quite true. This video does a good job of explaining your exact issue: https://youtu.be/RBM03RihZVs?t=842

That link should take you the right time in the video, but if it doesn't, it's at 14:02
That only says the children inside of a context provider don't have to be client components, but certainly any component consuming data from the context provider has to be a client component
Whereas if passed by props, the children consuming the data can remain server components
maybe I misunderstand, but what's wrong with simply importing the large object in the files you need it from?
I'm fetching it, so I don't have it as a file to import it
@୧ʕ•̀ᴥ•́ʔ୨ But it's a static object so it's not really state, just a large json object. I could use a context provider but that's probably overkill and not what context providers are intended for. On the other hand I don't want to prop drill the object into all the components. Any ideas?
Transvaal lion
sorry if it's an obvious thing but why not just import it from a file, or if it comes from the backend then the only other way I can think of is by querying everytime you need it and use caching?
It comes from an API, not from my code
It's json returned by the API
It gets fetched in page.tsx and ideally I'd like to be able to access it in nested components
@୧ʕ•̀ᴥ•́ʔ୨ I'm fetching it, so I don't have it as a file to import it
right, i see. i'm also interested in a nice solution for this. would be great to have a form of context for only passing pure data which can be used in both rsc & client
Lesser Goldfinch
Hi, in your use case use Next.js ˋfetchˋ everywhere you need the data. It caches the result and would not ask the api again.
So I guess then fetch inside server components and context in client ones
Lesser Goldfinch
Yes, unless you get the same effect with controlling browser cache. https://nextjs.org/docs/app/api-reference/functions/fetch. I still did not use fetch client side.