State Management with React Context 3 exercises

Pass Data from the Server to the Client Context

The first action takes place in our Layout component.

We already have created a cart in there, so now we'll add it to the CartProvider:

const cart = await getCart()
// inside the return
<CartProvider cart={cart}>
<Header clearCartAction={clearCartAction} />


Loading solution


00:00 I've copied the contents of the cart context directory into the cart context with initial state directory, install my modules, and run it, and I'm ready to go. So let's go take a look over at our layout because that's actually where all of the action is going to happen. So in the layout, we have the current cart, but we're just ignoring it.

00:19 So what we want to do is we want to go and send that cart to our cart provider. Of course, it doesn't know it needs a cart. So let's go over into our cart provider and upgrade that. So we're going to take a new property called cart, and then I'll take cart and map it to initial cart, and then I'll pass that onto our useCartState hook.

00:40 UseCartState will take that initial cart, and then use it as the initial value. Let's save, and let's try it out. Now when I hit refresh, it starts at two in our cart context, and I bring it up, we've got our cart context, we're good to go from the initial render.

00:59 So actually, let's go take a look at the ViewPageSource. So we can see that two hidden in all of the HTML, and that two from the server tells us that we are properly initializing that cart context on the server with that cart. So that on the initial server render,

01:18 even though it is a client component, it does render on the server, we're getting the correct cart count right there. You can also see if you scroll a little bit further down in your HTML, the RSC code that connects the server with the client. You can actually see that the cart is being serialized by

01:36 React and then passed on to the client. Then during client hydration, that cart is then hydrated on a client so that the context on the server matches the context on the client. Now all this is being done because over here in the layout,

01:51 we are passing that cart as a property from the RSC into that cart context. When you pass properties from an RSC into a client component, they are serialized by React. So why don't you join me in the next exercise where we wrap up our React state implementation of

02:10 our e-commerce app by adding the product reviews functionality.