Black Sheep Code
rss_feed

In the previous post about making responsive cookies for React, I mention that the you'll see a flash of the default value, before the actual clientside cookie appears.

This is because my blog is server rendered using NextJS, and server doesn't have access to the clientside cookies, and so renders using the default value. When the page hits the browser, the clientside useEffect occurs and the value is replaced with the cookie.

However, the cookie is available to the server, it's attached to the request for the page.

☝️ Interactive demo

Name: John Doe

Age: 30

Server cookie: default-value-for-server-cookie

Click 'Update User' to generate a random user'

Refresh the page, observe that this compoent briefly flashes the default user.

☝️ Interactive demo

Name: John Doe

Age: 30

Server cookie: default-value-for-server-cookie

Refresh the page, observe that this component starts with the correct user.

Attaching the cookie server side, in a React Server Component (RSC) is straight forward, we simply use the cookies() function.

We use this in a simple RSC, and then pass the values into our client component.



Questions? Comments? Criticisms? Get in the comments! 👇

Spotted an error? Edit this page with Github