Next.js Discord

Discord Forum

Get layout data from page

Unanswered
Polar bear posted this in #help-forum
Open in Discord
Polar bearOP
Hi, I’m using Next.js with the App Router and have a question about Context and Server/Client components.

Current setup:

* Layout is a Server Component that only wraps a Context Provider with empty/default values.
* Navbar is a Client Component that consumes the Context, showing default/loading values initially.
* Each Page is a Server Component that fetches data from the database, and currently uses a small Client Component to set that data into the Context for the Navbar.

Goals:

1. Fetch DB data server-side in the Page.
2. loading.tsx should display instantly when navigating.
3. Navbar should display data from the DB, but fetching it in Layout causes it to be prefetched, which results in double-fetching (once in Page, once in Layout). This can’t be fixed with React cache.
4. The Navbar value should be client-side changeable for optimistic updates.

Problem:
I don’t want a Client Component like this on every Page just to set the Context.

Question:
Is there a better way to structure this in Next.js so that:

* Server-side Page data can populate the Context for Client Components.
* Navigation and loading.tsx still work instantly without double-fetching.

0 Replies