How to pass data fetched in layout.js to all the Pages (Server components) ?
Answered
American Sable posted this in #help-forum
American SableOP
I have multi-tenant app and I'm fetching styles on first time page load in Layout file instead of in each page. How to pass that data to server components?
Answered by joulev
server. if you are using
https://nextjs.org/docs/app/building-your-application/caching#request-memoization
fetch it should work automatically no need to React.cache. simply call the fetch in both the pages and the layout.https://nextjs.org/docs/app/building-your-application/caching#request-memoization
9 Replies
@American Sable I have multi-tenant app and I'm fetching styles on first time page load in Layout file instead of in each page. How to pass that data to server components?
do the fetching in each individual page again. if you are not using
fetch, use React.cache to deduplicate the request (so despite you calling the request in multiple places, it is only run once)pages and layouts are run in parallel so cannot share data between them, they can only read from and write to a shared cache (
React.cache)American SableOP
I am using fetch function, but see how I can integrate React.cache
Do React.cache works on server side or client side?
server. if you are using
https://nextjs.org/docs/app/building-your-application/caching#request-memoization
fetch it should work automatically no need to React.cache. simply call the fetch in both the pages and the layout.https://nextjs.org/docs/app/building-your-application/caching#request-memoization
Answer
if you are fetching in client components, you can pass data via contexts, but i prefer to use data fetching libraries like swr/react-query which has automatic global state management for you, for example https://swr.vercel.app/docs/advanced/performance.en-US#deduplication
American SableOP
So, For fetch function Next js will check if the same api url was hit again it will just provide results from cache.
yeah
American SableOP
Thanks for the help