Next.js Discord

Discord Forum

How does nextjs know the right state for client components?

Unanswered
Brown bear posted this in #help-forum
Open in Discord
Brown bearOP
Hello, I was expecting to get hydration error, I am doing this I have a component in which I am using hooks simplified version is like this:

"use client";

export function Dashboard() {
    const  isAuthenticated = useAuth();

    return isAuthenticated ? "Dashboard":"Signin"
}


in my RootLayout I have an AuthProvider

 
const RootLayout = async ({ children }: RootLayoutProps) => {
    const isAuthenticated = await validateSession();

    return (
<html lang={currentLocale} className={cn(PrimaryFont.variable)}>
 <body>
  <AuthProvider initialIsAuthenticated={isAuthenticated}>      <main>{children}</main>        </AuthProvider>
 </body>
</html>
    );
};



When I refreshed the browser, it fetches the page and in the response it has the correct content, if I am loggedIn it shows initially Dashboard otherwise it shows Signin, how does it know that?

3 Replies

Brown bearOP
anybody pls?
Transvaal lion
Not sure what auth solution you are using, but to me it looks like validateSession gets the initial isAuthenticated value on the server and passes it to the AuthProvider context as an initial value. useAuth has the correct state from the beginning because the context in your AuthProvider has already gotten an initial value from the server in your RootLayout
@Transvaal lion Not sure what auth solution you are using, but to me it looks like `validateSession` gets the initial `isAuthenticated` value on the server and passes it to the `AuthProvider` context as an **initial value**. `useAuth` has the correct state from the beginning because the context in your `AuthProvider` has already gotten an initial value from the server in your RootLayout
Brown bearOP
I am getting the isAuthenticated state on the server and passing it to AuthProvider, but a client component accesses that value through a hook, so when I requested the page from the server and I checked the network in browser, I saw the content had the initial value correctly, I thought it will initially use the default value and only after hydration happens it will be updated