Working with React Server Components
This guide provides information about working with React Server Components in your Hydrogen app. To learn how React Server Components work in the context of Hydrogen, refer to React Server Components overview.
Fetching data on the serverAnchor link to section titled "Fetching data on the server"
All data fetching happens on the server and is never exposed to the client, unless you explicitly fetch data in a client component.
Hydrogen provides the following ways to fetch data from server components:
useShopQuery: A hook that makes server-only GraphQL queries to the Storefront API.
fetchSync: A hook that makes API requests and is the recommended way to make simple fetch calls on the server and the client.
useQuery: A hook that executes an asynchronous operation like
fetchin a way that supports Suspense. You can use this function to call any third-party APIs or perform any async tasks.
To learn how to fetch data from third-party sources, refer to Data sources.
The following example shows a server component (
Product.server.jsx) that uses the
useShopQuery hook to fetch data. The data is passed to a client component (
WishListButton.client.jsx) that uses state:
Fetching data on the clientAnchor link to section titled "Fetching data on the client"
To make a third-party HTTP request on the client, use the
fetchSync hook within a Suspense boundary:
npm package. You can use Hydrogen's
suspendFunction utility to create a version of the SDK which supports Suspense data-fetching:
Sharing data between client and serverAnchor link to section titled "Sharing data between client and server"
Hydrogen provides a
useServerProps() hook with a
setServerProps() helper function, which allows you to re-render server components with new data. You can use
setServerProps() for UI states that shouldn't persist in the URL. Any data set with
setServerProps() will be reset when the user navigates to a new page.
Using Anchor link to section titled "Using Context in React Server Components"
Context in React Server Components
React developers commonly use
Context to share state among many different components in a render tree, without having to drill props down to each individual component.
Currently, you can't use
Context inside server components because server context isn't yet available in React. However, you can use
Context inside client components.
The following example shows how to use
Context in the
CartProvider client component: