This article is a part of the series "Using cookies in React applications"
Using cookies in React Server Components to avoid a flash the incorrect content.
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.
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.
11export function UserProfileRsc(props: UserProfileRscProps) {
12 const cookieStore = cookies();
13
14 const user = cookieStore.get("user-2");
15 const serverCookie = cookieStore.get("server-cookie");
16
17 return (
18 <UserProfile3 initialUser={user ? JSON.parse(user?.value) : defaultUser} initialServerCookie={serverCookie?.value ?? "default-value-for-server-cookie"} />
19 )
20}
Questions? Comments? Criticisms? Get in the comments! 👇
Spotted an error? Edit this page with Github