Next.js Discord

Discord Forum

Fetching content for common components in layout

Answered
Cornish Rex posted this in #help-forum
Open in Discord
Cornish RexOP
I want to implement common header and footer for website and need to fetch content for them in the layout component. What I can observe is the fetch requestin the layout gets called mutiple times, and that too every time the route is changed. What is the right way I should be doing this?
Answered by Marchy
Ah, in that case I'd just put them in their own server components and import those into the layout. That way you can configure the caching accordingly. It will get called multiple times, especially in dev, but you should be able to cache it pretty heavily
View full answer

13 Replies

the right thing is to not fetch data in your layout. The layout is there to lay-out your components.
one possible way is to create two components (Header, Footer) and then include them in your layout and lay-out them where you want to have them. Inside your header and your footer you call you data source
What content are you needing to fetch?
You can fetch in layout, but that might be a better spot for things like analytics. I wouldn't expect a header and footer to need a hard fetch for data
maybe some login stuff or something like that..
Cornish RexOP
i am building header and footer content from headless cms
so just want to fetch the content
so should i be fetching this content in header/footer files itself?
Ah, in that case I'd just put them in their own server components and import those into the layout. That way you can configure the caching accordingly. It will get called multiple times, especially in dev, but you should be able to cache it pretty heavily
Answer
Cornish RexOP
okkk
i will try this and will ask if does not work as expected
Cornish RexOP
it does
thank you