Injecting Server Data into Client Context
Explore how to inject data fetched on the server into client-side React context in Next.js. Understand the Provider Wrapper pattern that bridges server data to client components without prop drilling or extra fetches. Gain practical knowledge to manage global state like user sessions or themes efficiently.
In the lesson “Local State and Context,” we explored a pattern where we wrapped a server component inside a client-side context provider. In that scenario, the Provider managed its own state (like cartCount) entirely in the browser. It did not receive any initial data from the server. The goal there was simple: give interactive state to specific islands of the UI, while letting the rest remain static Server Components.
But this raises a new question: What’s the best way to share data that originates on the server?
Consider a RootLayout that fetches the current user’s session. How do we make this user object available to a deep-in-the-tree <Avatar /> client component? We could drill props, but that’s messy. Or we could use a client-side provider, but why refetch data on the client that the server already has?
This is the specific problem the Provider Wrapper pattern solves. It allows a Server Component to fetch data once and “inject” it into a context that client components can consume.
The pattern in action
To make ...