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
:
Now we need to update the CartProvider
to accept the cart
property.
Updating the Cart Provider
In the CartProvider
inside of CartContext.tsx
, we'll introduce a new property called cart
, which is then mapped to initialCart
. This initialCart
is passed on to our useCartState
hook.
The useCartState
takes the initialCart
and uses it as its initial value.
Checking Our Work
After saving these changes, refreshing the app starts the cart count at two, confirming that we have the data we expect from the initial render.
Checking the rendered HTML with "View Source", we can see further proof that everything is working.
Note the HTML that contains the cart count of 2
:
Even though the Header is a client component, it does render on the server.
Further down in the rendered html is the React Server Component code that connects the server with the client.
During client hydration, React serializes the properties passed from an RSC into a client component. This ensures that the cart context remains consistent between the server and client.
We can see the encoded JSON for the initial cart data:
Recapping the Context Initialization
Our context is being initialized because of the setup we did in the Layout
component.
In the Layout
, which is a React Server Component, we pass the cart
as a prop to the CartContext
, which is a Client Component.
When you pass properties from an RSC into a client component, they are serialized by React.
In the next exercise, we'll wrap up our React state implementation of our ecommerce app by adding the product reviews functionality.