Server state

As you build your Hydrogen app with React Server Components, you'll likely need to update state on the server. Sharing state information between the client and server is important for common tasks, like page routing.

This guide describes how to manage your server state during your development process.

How state works

The state object is core to React Server Components. Hydrogen provides a useServerState() hook with a setServerState() helper function, which allows components to paginate within collections, programmatically switch routes, or do anything that requires new data from the server.

For example, you can take geo-location co-ordinates and set them as serverState to provide a new hydrated experience for the current location:

Managing server state

The most basic example of state is the page prop, which Hydrogen manages for you whenever your URL location changes. The server state is passed as a prop to page components. However, you can set any state that you want within client components using the useServerState hook:

Whenever you modify the state with setServerState(), Hydrogen automatically makes a hydration request to the server component. Your app tree is updated based on the result of that hydration request.

Example

The following example shows a page that queries a specific product ID based on server state:

Next steps