NextJS RSC (React Server Component)) State or Global Variables need to be updated before send to client

I have a code define some global variable like h1, and setting from child component (dynamic component loading), but the variables are not updated in current context.

I also try with state management on server like redux or zustand


export let h1 = "";

export function setH1(newH1: string){
   h1 = newH1;
}; 

export default async function Page(){
setH1("Heading set from Page");

return <div>
    <h1>{h1}</h1> //Rendered Heading set from Page
    <ChildComponent />
</div>
}

//child-component.tsx (Server Component)
import {h1, setH1} from "./page.tsx";

export async function ChildComponent() {
   const postData = await fetch("https://example.com/posts");
   setH1("Heading from ChildComponent" + postData.title)
   return <div>{h1}</div> //Rendered: Heading from ChildComponent + postData.title
}

But the return html from server rendering not as expected

<div>
   <h1>Heading set from Page</h1>
   <div>
        Heading from ChildComponent Lorem Ipsum...
   </div>
</div>

I am expected a solution to update the variable before final rendering to the client, some thing like Server Context, re-render page when dependency variables changes, or some modification life-cycle method?

<div>
   <h1>Heading from ChildComponent Lorem Ipsum...</h1>
   <div>
        Heading from ChildComponent Lorem Ipsum...
   </div>
</div>

Leave a Comment