Next.js Discord

Discord Forum

Sharing state across server components in a layout.

Answered
Ben Jackson posted this in #help-forum
Open in Discord
I'm using Next 14 with Supabase. My layout.tsx runs subabase.getUser() to fetch a user object. I need the user information in my page.tsx component and my Nav component. I don't want to have to run .getUser() (it calls the supabase API) in both components so it would be great to run it once in my layout.tsx and pass it to both children.

I realise I can pass it down as a prop to Nav. But what about the children (page content). Also I'd rather have some sort of Context solution so that I don't have to do too much prop drilling as my app increases in complexity.

Is this possible? My layout.tsx looks something like the following:

<body> <Nav /> <main> {children} </main> </body>)

Thanks in advance!
Answered by Ray
https://nextjs.org/docs/app/building-your-application/caching#react-cache-function
I would create a function like getUser with react cache so you can call it multiple time
View full answer

12 Replies

https://nextjs.org/docs/app/building-your-application/caching#react-cache-function
I would create a function like getUser with react cache so you can call it multiple time
Answer
@Ray https://nextjs.org/docs/app/building-your-application/caching#react-cache-function I would create a function like getUser with react cache so you can call it multiple time
Thanks Ray. I'm probably getting something wrong but I thought this cache was for a different use case. i.e. if I did something like the following, wouldn't that cache be shared across all on my site?

export const getUser = cache(async (supabase) => { const {user} = supabase.getUser() return user })
react cache is cache per request
OK so just so I understand - each page load would clear the cache and fetch the user again? But if every component on that page load used "getUser" they would all use the same cached user object?
If so that's exactly what I'm looking for.
yes
Thanks Ray.
np, you can test with it
I'm assuming client components can't also grab that user object too can they?
I would use server-only package to ensure that the function is not importing/using on client component
pass it from server component or create an api route and fetch client side if you need the user object in client component